Skip to content

Instantly share code, notes, and snippets.

@jasonknight
Last active July 31, 2019 21:29
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 jasonknight/fc7fe23b5f4dfc929636b9ccbebc8ae6 to your computer and use it in GitHub Desktop.
Save jasonknight/fc7fe23b5f4dfc929636b9ccbebc8ae6 to your computer and use it in GitHub Desktop.
Reversing a linked list with a stack
class Node
attr_accessor :value,:next_node
def initialize(val,nxt)
@value = val
@next_node = nxt
end
end
class Stack
attr_accessor :data
def initialize(d=nil)
@data = d
end
def push(node)
node.next_node = @data
@data = node
end
def pop
return @data if not @data
node = @data
@data = @data.next_node
return node
end
end
def reverse_nodes(stack)
return stack.data
end
def print_values(node)
if node
print "#{node.value} --> "
print_values(node.next_node)
else
print "nil\n"
end
end
s = Stack.new
ll = Node.new(1,Node.new(2,Node.new(3,nil)))
print_values(ll)
node = ll
while node
s.push(node.clone) # because ruby passes by reference!
node = node.next_node
end
print_values(reverse_nodes(s))
@jasonknight
Copy link
Author

Consider reading this: https://www.cs.bu.edu/teaching/c/stack/linked-list/ which explains stacks waaaay better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment