Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save umasenthil/b65e7825a744c777c006 to your computer and use it in GitHub Desktop.
Save umasenthil/b65e7825a744c777c006 to your computer and use it in GitHub Desktop.
class Linked_list
attr_accessor :value, :next_node
def initialize(value, next_node =nil)
@value = value
@next_node = next_node
end
end
class Stack
attr_accessor :data
@head = nil
def initialize
@data = nil
end
def ==
end
def push(data)
if @head
data.next_node = @head
@head = data
else
@head = data
end
end
def pop
node = @head
if (node)
temp = node
@head = @head.next_node
return temp.value
else
puts "Empty list"
return nil
end
end
def print_list
node = @head
while node do
if(node)
puts node.value
node = node.next_node
else
puts "No more node"
return
end
end
end
def reverse_list
current = @head
count = 1
while current do
puts "iteration #{count}"
count = count +1
if (current == @head)
prev = nil
# puts "execute for head alone"
end
#puts "Current value before change #{current.value}"
temp = current.next_node
current.next_node = prev
#puts "transistion current.next #{current.next_node.value}"
prev = current
#puts "previous #{prev.value}"
current = temp
end
@head = prev
#puts "change head to prev #{@head.value}"
end
end
stack = Stack.new
stack.push(Linked_list.new(1))
stack.push(Linked_list.new(2))
stack.push(Linked_list.new(3))
stack.print_list
stack.reverse_list
stack.print_list
stack.pop
stack.print_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment