Skip to content

Instantly share code, notes, and snippets.

@framallo
Forked from pshushereba/gist:1621565bd00272eb285f
Last active March 11, 2016 01:39
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 framallo/986daac8216848d44a47 to your computer and use it in GitHub Desktop.
Save framallo/986daac8216848d44a47 to your computer and use it in GitHub Desktop.
linked1
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
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
# 37
# 99, 37
# 12, 99
# 12, 99 # next_node = 99
# 12, nil # set next_node = prev_node which is nil
# prev_node = 12
# node = 99
# here we go again
# next_node = 37
# 99, 12 # set next_node = prev_node which is 12
# prev_node = 99
# node = 37
# here we go again
# next_node = nil
# 37, 99
# prev_node = 37
# node = nil
# while node wil not execute again
# We return 37. And this is how it would look like
# 12, nil
# 99, 12
# 37, 99
def reverse_list(node)
prev_node = nil
while node
next_node = node.next_node
node.next_node = prev_node
prev_node = node
node = next_node
end
prev_node
end
def reverse_list2(node)
prev_node = nil
while node
next_node = node.next_node
node.next_node = prev_node
prev_node = node
node = next_node
end
prev_node
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
@data = @data.next_node
end
def reverse
end
def print_nodes
print_values(@data)
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
# stack = Stack.new
# stack.push(37)
# stack.push(99)
# stack.push(12)
#
# stack.print_nodes
print_values(node3)
puts "-------"
revlist = reverse_list(node3)
print_values(revlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment