Skip to content

Instantly share code, notes, and snippets.

@okkez
Created November 3, 2009 06:57
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 okkez/224851 to your computer and use it in GitHub Desktop.
Save okkez/224851 to your computer and use it in GitHub Desktop.
KansaiWorkshop38's answer
class Stack
class EmptyError < StandardError
end
class Node
attr_accessor :prev, :data
def initialize(prev, data)
@prev = prev
@data = data
end
end
def initialize
@cur = nil
end
def empty?
@cur.nil?
end
def push(val)
if @cur
new = Node.new(@cur, val)
@cur = new
else
@cur = Node.new(nil, val)
end
val
end
def pop
raise EmptyError if empty?
popped = @cur
@cur = @cur.prev
popped.data
end
def size
count(@cur, 0)
end
private
def count(node, memo)
return memo if node.nil?
if node.prev
count(node.prev, memo+1)
else
memo + 1
end
end
end
require 'test/unit'
require 'stack'
class TestStack < Test::Unit::TestCase
def setup
@stack = Stack.new
end
def test_empty
assert @stack.empty?
end
def test_size
assert_equal 0, @stack.size
end
def test_empty_pop
assert_raise(Stack::EmptyError){
@stack.pop
}
end
def test_push_and_pop
@stack.push(3)
assert_equal 3, @stack.pop
end
def test_push_and_size
@stack.push(3)
assert_equal 1, @stack.size
end
def test_push_push_and_size
@stack.push(3)
@stack.push(5)
assert_equal 2, @stack.size
end
def test_push_and_empty
@stack.push(3)
assert !@stack.empty?
end
def test_push_push_pop_and_size
@stack.push(3)
@stack.push(5)
@stack.pop
assert_equal 1, @stack.size
end
def test_push_push_and_pop
@stack.push(3)
@stack.push(5)
assert_equal 5, @stack.pop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment