Skip to content

Instantly share code, notes, and snippets.

@roryokane
Created March 31, 2014 07:04
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 roryokane/d47920d59732773b872f to your computer and use it in GitHub Desktop.
Save roryokane/d47920d59732773b872f to your computer and use it in GitHub Desktop.
Implementations of https://www.interviewcake.com/question/largest-stack ’s official answer in Ruby – a buggy, wrong implementation of a stack with #get_largest
class MaxStack
attr_reader :stack, :largests_stack # for debugging
def initialize
@stack = []
@largests_stack = []
end
def push(item)
@stack.push(item)
if @largests_stack.empty? || item >= @largests_stack.last
@largests_stack.push(item)
end
item
#@largest = [@largest, item].max
end
def pop()
item = @stack.pop
if item == @largests_stack.last
@largests_stack.pop
end
item
end
def get_largest
@largests_stack.last
#if @stack.empty? throw "no values"
#@stack.max
end
end
class MaxStack
attr_reader :stack, :largests_stack # for debugging
def initialize
@stack = []
@largests_stack = []
end
def push(item)
@stack.push(item)
if item >= @largests_stack.last
@largests_stack.push(item)
end
item
#@largest = [@largest, item].max
end
def pop()
item = @stack.pop
if item == @largests_stack.last
@largests_stack.pop
end
item
end
def get_largest
@largests_stack.last
#if @stack.empty? throw "no values"
#@stack.max
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment