Skip to content

Instantly share code, notes, and snippets.

@PandaWhisperer
Last active April 13, 2016 18:03
Show Gist options
  • Save PandaWhisperer/ded501bc16b343c3333ba2caac715faf to your computer and use it in GitHub Desktop.
Save PandaWhisperer/ded501bc16b343c3333ba2caac715faf to your computer and use it in GitHub Desktop.
# LinkedList implementation as given in the problem assignment
class LinkedList
attr_accessor :payload, :next_element
def initialize(payload, next_element)
@payload, @next_element = payload, next_element
end
end
# output_list implementation as given in the problem assignment
def output_list(list)
return if list.nil?
puts list.payload
output_list(list.next_element)
end
require "./linked_list"
# Stack implementation as given in problem assignment
class Stack
attr_reader :data
def initialize
@data = nil
end
# Push an item onto the stack
def push(element)
@data = LinkedList.new(element, @data)
end
# Pop an item off the stack.
# Remove the last item that was pushed onto the stack
# and return it to the user
def pop
unless @data.nil?
element = @data.payload
# advance pointer
@data = @data.next_element
# return element
element
end
end
end
require 'minitest/autorun'
require './stack'
describe Stack do
before do
@stack = Stack.new
end
describe 'when empty' do
it "pop doesn't return anything" do
@stack.pop.must_equal nil
end
end
describe 'adding elements' do
it 'returns elements in reverse order of adding' do
@stack.push 1
@stack.push 2
@stack.push 3
@stack.pop.must_equal 3
@stack.pop.must_equal 2
@stack.pop.must_equal 1
@stack.pop.must_equal nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment