Skip to content

Instantly share code, notes, and snippets.

@michellejanosi
Created June 9, 2017 17:09
Show Gist options
  • Select an option

  • Save michellejanosi/d86e880dd275e36df091f309adf4dce3 to your computer and use it in GitHub Desktop.

Select an option

Save michellejanosi/d86e880dd275e36df091f309adf4dce3 to your computer and use it in GitHub Desktop.
Linked List 1
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
class Stack
attr_reader :data
def initialize
@data = nil
end
# Push a value onto the stack
def push(value)
@data = LinkedListNode.new(value, @data)
end
# Pop an item off the stack.
# Remove the last item that was pushed onto the
# stack and return the value to the user
def pop
# store top node value in a variable
top_node_value = @data.value
# override top node with next node in stack (pop off top value)
@data = @data.next_node
# return top node value
top_node_value
end
end
def print_values(list_node)
if list_node
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
def reverse_list(list)
# create stack
stack = Stack.new
# loop through linked list and
while list
# push each node onto the stack
stack.push(list.value)
# move to next node in original linked list
list = list.next_node
end
# return stack
stack.data
end
node1 = LinkedListNode.new(43)
node2 = LinkedListNode.new(109, node1)
node3 = LinkedListNode.new(11, node2)
node4 = LinkedListNode.new(87, node3)
print_values(node4)
revlist = reverse_list(node4)
print_values(revlist)
# => 87 --> 11 --> 109 --> 43 --> nil
# => 43 --> 109 --> 11 --> 87 --> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment