Skip to content

Instantly share code, notes, and snippets.

@amyhenning
Created October 31, 2018 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amyhenning/7e6a043a504098f1e59783ff41c208bf to your computer and use it in GitHub Desktop.
Save amyhenning/7e6a043a504098f1e59783ff41c208bf to your computer and use it in GitHub Desktop.
class LinkedListNode
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
def kth_to_last_node(k, head)
# create two pointers at the head node
trailing_pointer = head
leading_pointer = head
# set the leading_pointer k nodes ahead of the trailing_pointer
k.times do
leading_pointer = leading_pointer.next
end
# advance both leading_ and trailing_pointers. When the leading_pointer reaches the last node, the trailing_pointer will be k nodes from the end.
until leading_pointer.next == nil
trailing_pointer = trailing_pointer.next
leading_pointer = trailing_pointer.next
end
puts "The value of the Kth node from the end of the linked list is #{trailing_pointer.value}"
end
end
a = LinkedListNode.new("Angel Food")
b = LinkedListNode.new("Bundt")
c = LinkedListNode.new("Cheese")
d = LinkedListNode.new("Devil's Food")
e = LinkedListNode.new("Eccles")
a.next = b
b.next = c
c.next = d
d.next = e
a.kth_to_last_node(2, a)
# returns the node with value "Devil's Food" (the 2nd to last node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment