Pregunta de entrevista de Google

How would you implement a stack with the additional operation of getMin?

Respuestas de entrevistas

Anónimo

27 mar 2010

I would use two stacks. Pop from 1 to other while checking to see the minimum number. When u r done, re-push from stack2 back to S1 to get the original stack. return minimum. Stack S1; //stack contains data of ints int min=0; //initialize min int Stack::getmin(Stack& S1) { Stack S2; //Transfer all from S1 to S2 while(!S1.isEmpty()) { int temp = S1.pop(); if(temp

Anónimo

27 mar 2010

in the above answer, please change the "int min to 1000000". I intended to initialize to a high number.

Anónimo

18 ene 2011

Jake, It's not that simple. Say you pushed 1, 2, and 3, and then popped 1. If you just keep track of the minimum that was pushed, you would still have 1 but that's not even in the stack anymore. You also can't just erase the value if you pop it off, because then a situation that was like push 1, 1, 2, 3, pop 1 would give you the wrong answer (i.e. should still be 1).

Anónimo

23 mar 2011

template class gmStack{ private Stack S; Stack m; public gmStack(); ~gmStack(); void push(item *); item * pop(); item * getMin(); } void gmStack::push(item * i){ S.push(i); item *t=m.pop(); m.push(t); if(i<=t) m.push(i); } item *gmStack::pop(){ item *t=m.pop(); item *r=S.pop(); if(t!=r) m.push(t); return r; } item *gmStack::getMin(){ item *t=m.pop(); m.push(t); return t; } gmStack::gmStack(){ S=new Stack(); m=new Stack(); } gmStack::~gmStack(){ delete S; delete m; }

Anónimo

1 feb 2010

Use two stacks, one for the real stack, and one to hold the list of minimums. When you pop, check to see if its the minumum. If so, also pop it off the second stack.

Anónimo

30 mar 2010

Declare two stacks. One is the real stack of data. The other is a temporary one. Pop from real to temp. As u pop, check for minimum, save it in a variable. When finished, pop from temp stack back to real stack. Stack S1; //stack contains data of ints int Stack::getmin(Stack& S1) { int min=1000000; //initialize min Stack S2; //Transfer all from S1 to S2 while(!S1.isEmpty()) { int temp = S1.pop(); if (temp

Anónimo

22 abr 2010

Wouldn't be easier to just have a variable min and compare to each int as you push it onto the stack: int min=firstInt; if(min>=nextPush) min=nextPush; Really you could just make that into a separate method too and just call it with push . . . or maybe I'm over simplifying.