Skip to content

Instantly share code, notes, and snippets.

@iaintshine
Created August 14, 2014 16:52
Show Gist options
  • Save iaintshine/b9de4b66a58652c5c9f5 to your computer and use it in GitHub Desktop.
Save iaintshine/b9de4b66a58652c5c9f5 to your computer and use it in GitHub Desktop.
A Ruby implementation of a Stack data structure using a Single Linked List
require 'test/unit'
# LIFO
class Stack
include Enumerable
Node = Struct.new :element, :next
attr_reader :head, :size
def initialize(items = [])
@head = nil
@size = 0
items.to_ary.each { |element| push element }
end
# add element add the top of the stack
def push(element)
n = Node.new element, @head
@head = n
@size += 1
element
end
# remove and return the element from the top of the stack
def pop
return nil unless @head
n = @head
@head = n.next
@size -= 1
n.element
end
# return but not remove the element at the top of the stack
def top
@head && @head.element
end
def empty?
@size == 0
end
def clear
@head = nil
@size = 0
end
def each
return unless @head
n = @head
while n
yield n.element
n = n.next
end
end
end
if __FILE__ == $0
class TestStack < Test::Unit::TestCase
def setup
@stack = Stack.new
end
def teardown
@stack.clear
end
def test_init_state
assert_equal 0, @stack.size
assert_equal nil, @stack.top
assert @stack.empty?
end
def test_simple
element = 1
@stack.push element
assert_equal element, @stack.top
assert_equal 1, @stack.size
assert [email protected]?
assert_equal element, @stack.pop
assert_equal 0, @stack.size
assert @stack.empty?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment