Created
July 12, 2016 03:51
-
-
Save astronomy88/07dc2d7914bf14f8727001d5ee939d29 to your computer and use it in GitHub Desktop.
Stack implementation with Linked Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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