Created
June 24, 2013 16:11
-
-
Save HoyaBoya/5851259 to your computer and use it in GitHub Desktop.
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 Node | |
attr_accessor :next | |
attr_accessor :value | |
end | |
def traverse_linked_list(start_node) | |
current_node = start_node | |
while current_node != nil do | |
puts "VALUE #{current_node.value}" | |
current_node = current_node.next | |
end | |
end | |
def reverse_linked_list(start_node) | |
current_node = start_node | |
previous = nil | |
while current_node != nil | |
# store the next pointer into temp | |
temp = current_node.next | |
# set the current next to the previous | |
current_node.next = previous | |
# update the previous node to the current node | |
previous = current_node | |
# move to next node which has been saved in temp | |
current_node = temp | |
end | |
end | |
node_c = Node.new | |
node_c.value = "C" | |
node_c.next = nil | |
node_b = Node.new | |
node_b.value = "B" | |
node_b.next = node_c | |
node_a = Node.new | |
node_a.value = "A" | |
node_a.next = node_b | |
traverse_linked_list(node_a) | |
reverse_linked_list(node_a) | |
traverse_linked_list(node_c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment