Skip to content

Instantly share code, notes, and snippets.

@pdbradley
Created January 17, 2017 20:22
Show Gist options
  • Save pdbradley/a5047cee05bdb55666b5df9e08614616 to your computer and use it in GitHub Desktop.
Save pdbradley/a5047cee05bdb55666b5df9e08614616 to your computer and use it in GitHub Desktop.
linked list with recursive reverse print
class Node
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
node1 = Node.new(12)
node2 = Node.new(37, node1)
node3 = Node.new(99, node2)
# 99 --> 37 --> 12 --> nil
class Stack
attr_reader :head
def initialize
@head = nil #nil pointer to the head
end
# Push a new node(value) on top of the stack
def push(value)
@head = Node.new(value, @head) #stack is a type pointer to node
end
def pop
returnValue = @head.value # Grab the value of the head(first) Node
@head = @head.next_node # make the head(first)Node, equal to the next Node of the current first Node
return returnValue # and return the value to the user
end
end
#list = 99 --> 37 --> nil
#rl = 37 -> 99 -> nil
#iteration 1:
# list = 99
# reversed_list.push(99)
# list = 37
# reversed_list.push(37)
def reverse_list(list)
reversed_list = Stack.new #Push elements into the reversed_list
while list #while the original list is not empty
reversed_list.push(list.value) #push the original value onto the reversed_list
list = list.next_node #go to the next value in the original list until done
end
# at the end, the reverse_list now has all the same items as list, but pushed in reverse order
return reversed_list.head #Once all nodes are pushed to stack, it returns this is the new stack
end
# 99 -> 37 -> 12
# recursive_print(99 -> 37 -> 12)
# recursive_print(37 -> 12)
# recursive_print(12)
# recursive_print(nil)
# print 12
# print 37
# print 99
def recursive_print(list)
if (list.nil?)
return
else
# print "#{list.value} " if you uncomment this it is a normal print (not reverse)
recursive_print(list.next_node)
print "#{list.value} "
end
end
def print_values(list_node)
print "#{list_node.value} --> " #prints the values of the nodes
if list_node.next_node.nil? #then loops through each node,checks to see if it is nil,
print "nil\n" #when it finds the node, it will print nil and return the value.
return
else
print_values(list_node.next_node) #
end
end
print_values(node3)
puts "-------"
revlist = reverse_list(node3)
print_values(revlist)
puts "Recursive Print"
recursive_print(node3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment