find the kth largest node in a linked list in ruby

To find the kth largest node in a linked list, we can use a sorting algorithm. One way to do this is to first convert the linked list to an array, sort the array in descending order, and then return the kth element of the array.

Here's some sample code to accomplish this in Ruby:

main.rb
class Node
  attr_accessor :value, :next

  def initialize(val)
    @value = val
  end
end

def kth_largest(head, k)
  # convert linked list to array
  arr = []
  curr = head
  while curr
    arr << curr.value
    curr = curr.next
  end

  # sort array in descending order
  arr.sort! { |a, b| b <=> a }

  # return kth largest element
  arr[k-1]
end

# example usage
head = Node.new(3)
head.next = Node.new(1)
head.next.next = Node.new(4)
head.next.next.next = Node.new(2)
puts kth_largest(head, 2) # output: 3
512 chars
31 lines

In the above example, the kth_largest method takes a head parameter representing the head of the linked list, and a k parameter representing which largest element we want to find. We convert the linked list to an array using a loop, sort the array using the sort! method with a block that compares elements in descending order, and then return the kth largest element using array indexing.

gistlibby LogSnag