Commit c63531f
Changed files (3)
lib
data_structures
spec
data_structures
lib/data_structures/linked_list_stack.rb
@@ -0,0 +1,59 @@
+class LinkedListStack
+ def initialize
+ @head = NullNode.new
+ end
+
+ def push(item)
+ @head.push(item)
+ end
+
+ def pop
+ @head.pop
+ end
+end
+
+class Node
+ attr_reader :data
+
+ def initialize(data)
+ @data = data
+ end
+
+ def push(item)
+ if @next
+ @next.push(item)
+ end
+
+ @next = Node.new(item)
+ end
+
+ def pop
+ if @next
+ if @next.is_tail?
+ result = @next.data
+ @next = nil
+ result
+ else
+ @next.pop
+ end
+ end
+ end
+
+ def is_tail?
+ @next == nil
+ end
+end
+
+class NullNode
+ def push(item)
+ if @next
+ @next.push(item)
+ else
+ @next = Node.new(item)
+ end
+ end
+
+ def pop
+ return @next.pop if @next
+ end
+end
spec/data_structures/linked_list_stack_spec.rb
@@ -0,0 +1,31 @@
+require "spec_helper"
+
+describe LinkedListStack do
+ let(:sut) { LinkedListStack.new }
+
+ context "when no items are pushed on to the stack" do
+ let(:result) { sut.pop }
+
+ it "should pop nil if there is nothing on the stack" do
+ result.should be_nil
+ end
+ end
+
+ context "when a single item is pushed on to the stack" do
+ it "should pop the last item pushed on to the stack" do
+ sut.push(1)
+ sut.push(2)
+ result = sut.pop
+ result.should == 2
+ end
+
+ it "should pop off each item in reverse order of how they were put on" do
+ (1..10).each do |n|
+ sut.push(n)
+ end
+ (10..1).each do |n|
+ sut.pop.should == n
+ end
+ end
+ end
+end
spec/spec_helper.rb
@@ -3,3 +3,5 @@ require_relative '../lib/sorting/bubble_sort'
require_relative '../lib/sorting/insertion_sort'
require_relative '../lib/sorting/quick_sort'
require_relative '../lib/sorting/merge_sort'
+
+require_relative '../lib/data_structures/linked_list_stack'