find the kth largest node in a linked list in go

To find the kth largest node in a linked list, we can use the following algorithm:

  1. Traverse the linked list to get its length n.
  2. Traverse the linked list again, this time stopping at the n-k+1th node, which will be the kth largest node.

Here's the Go code for the algorithm:

main.go
type Node struct {
   Value int
   Next *Node
}

func findKthLargest(head *Node, k int) *Node {
   // find the length of the linked list
   n := 0
   for curr := head; curr != nil; curr = curr.Next {
      n++
   }
   if k > n {
      return nil
   }
   // traverse the linked list to the n-k+1th node
   curr := head
   for i := 1; i < n-k+1; i++ {
      curr = curr.Next
   }
   return curr
}
395 chars
22 lines

We define a Node struct to represent a node in the linked list. The findKthLargest function takes the head of the linked list and the value of k as inputs, and returns a pointer to the kth largest node.

In the implementation, we first traverse the linked list to find its length n. If k is greater than n, there is no kth largest node, so we return nil.

Otherwise, we traverse the linked list again, stopping at the n-k+1th node, which is the kth largest node. Finally, we return a pointer to this node.

gistlibby LogSnag