Skip to content

Instantly share code, notes, and snippets.

Created October 31, 2018 03:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
class LinkedListNode
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
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 =
# 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 == nil
trailing_pointer =
leading_pointer =
puts "The value of the Kth node from the end of the linked list is #{trailing_pointer.value}"
a ="Angel Food")
b ="Bundt")
c ="Cheese")
d ="Devil's Food")
e ="Eccles") = b = c = d = 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