Skip to content

Instantly share code, notes, and snippets.

@HoyaBoya
Created April 8, 2014 14:37
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 HoyaBoya/10134527 to your computer and use it in GitHub Desktop.
Save HoyaBoya/10134527 to your computer and use it in GitHub Desktop.
Reverse a Singley Linked List
# PROBLEM:
# Given a singley linked list, reverse the list.
#
# SOLUTION:
# Nothing to tricky other to keep track of all the pointers when iterating through.
# Basic object to represent a linked list.
class Node
attr_accessor :next
attr_accessor :value
def initialize(options = {})
@next = options[:next]
@value = options[:value]
end
end
# Simple print method for a linked list
def traverse(root_node)
current_node = root_node
while current_node != nil
puts current_node.value
current_node = current_node.next
end
end
# The reverse implementation
def reverse(root_node)
previous_node = nil
current_node = root_node
while current_node != nil
next_node = current_node.next
current_node.next = previous_node
previous_node = current_node
current_node = next_node
end
end
# Build a linked list of A, B, C, D, E
node_e = Node.new(value: "E", next: nil)
node_d = Node.new(value: "D", next: node_e)
node_c = Node.new(value: "C", next: node_d)
node_b = Node.new(value: "B", next: node_c)
node_a = Node.new(value: "A", next: node_b)
traverse(node_a)
reverse(node_a)
traverse(node_e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment