Last active
July 31, 2019 21:29
-
-
Save jasonknight/fc7fe23b5f4dfc929636b9ccbebc8ae6 to your computer and use it in GitHub Desktop.
Reversing a linked list with a stack
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 :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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Consider reading this: https://www.cs.bu.edu/teaching/c/stack/linked-list/ which explains stacks waaaay better.