Created
February 28, 2018 05:08
-
-
Save stellamiranda/a189f499984ee5b2b81dde2fa4488585 to your computer and use it in GitHub Desktop.
You have a linked list ↴ and want to find the kth to last node.
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
#Write a method kth_to_last_node() that takes an integer kk and the head_node of a singly-linked list, and returns the kkth to last node in the list. | |
def kth_to_last_node(k, head) | |
if k < 1 | |
raise ArgumentError, "Impossible to find less than first to last node: #{k}" | |
end | |
# STEP 1: get the length of the list | |
# start at 1, not 0 | |
# else we'd fail to count the head node! | |
list_length = 1 | |
current_node = head | |
# traverse the whole list, | |
# counting all the nodes | |
while current_node.next | |
current_node = current_node.next | |
list_length += 1 | |
end | |
# if k is greater than the length of the list, there can't | |
# be a kth-to-last node, so we'll return an error! | |
if k > list_length | |
raise ArgumentError, "k is larger than the length of the linked list: #{k}" | |
end | |
# STEP 2: walk to the target node | |
# calculate how far to go, from the head, | |
# to get to the kth to last node | |
how_far_to_go = list_length - k | |
current_node = head | |
(0...how_far_to_go).each do |i| | |
current_node = current_node.next | |
end | |
return current_node | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment