This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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