Created
March 31, 2014 07:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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