Skip to content

Instantly share code, notes, and snippets.

@astronomy88
Created July 12, 2016 03:51
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 astronomy88/07dc2d7914bf14f8727001d5ee939d29 to your computer and use it in GitHub Desktop.
Save astronomy88/07dc2d7914bf14f8727001d5ee939d29 to your computer and use it in GitHub Desktop.
Stack implementation with Linked Lists
require './node'
class StackLinkedList
attr_reader :length
def initialize(item)
@first = Node.new(item)
@first.next = nil
@length = 1
end
def push item
@length += 1
oldfirst = @first
@first = Node.new(item)
@first.next = oldfirst
end
def pop
return nil if @length == 0
temp = @first.item
@first = @first.next
@length -= 1
temp
end
def each
current_node = @first
for i in 1..@length
if block_given?
yield current_node.item
current_node = current_node.next
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment