find the kth largest node in a linked list in php

To find the kth largest node in a linked list using PHP, we can follow the below algorithm:

  1. Traverse the linked list and create an array of all the nodes.
  2. Sort the array in descending order.
  3. Return the kth element of the sorted array.

Here's an implementation in PHP:

main.php
<?php 

class LinkedListNode {
    public $data;
    public $next;
    
    public function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }
}

class LinkedList {
    public $head;
    
    public function __construct() {
        $this->head = null;
    }
    
    // function to insert a new node
    public function insert($data) {
        $newNode = new LinkedListNode($data);
        if($this->head == null) {
            $this->head = $newNode;
        } else {
            $temp = $this->head;
            while($temp->next != null) {
                $temp = $temp->next;
            }
            $temp->next = $newNode;
        }
    }
    
    // function to get the kth largest node
    public function getKthLargest($k) {
        $arr = array();
        $temp = $this->head;
        while($temp != null) {
            array_push($arr, $temp->data);
            $temp = $temp->next;
        }
        rsort($arr);
        return $arr[$k-1];
    }
}

// example usage
$ll = new LinkedList();
$ll->insert(5);
$ll->insert(10);
$ll->insert(3);
$ll->insert(8);

echo $ll->getKthLargest(2); // output: 8
1143 chars
55 lines

In this implementation, we created a LinkedList class with two methods - insert to insert a new node and getKthLargest to get the kth largest element in the list.

In getKthLargest, we traversed the linked list and pushed each node's data into an array. We then sorted the array in descending order using rsort and returned the kth element of the sorted array.

gistlibby LogSnag