@Shravan: Push can be written more compactly as
void push(int num)
{
stk1.push(num);
if(stk2.isEmpty() || num<=stk2.top())
stk2.push(num);
}
Then don't forget min:
int min()
{
return stk2.top();
}
Dave
On Sep 6, 7:56 am, Shravan Kumar <[email protected]> wrote:
> void push(int num){
> if(stk1.isEmpty()){
> stk1.push(num);
> stk2.push(num);
> }
> else{
> if(num>stk2.top())stk1.push(num);
> else{stk1.push(num);stk2.push(num)}
> }
>
> }
>
> int pop(){
> int num=stk1.pop();
> if(num==stk2.top())stk2.pop();
> return num;
>
> }
>
> On Tue, Sep 6, 2011 at 6:12 PM, Prem Krishna Chettri
> <[email protected]>wrote:
>
>
>
> > Guys What the Issue Here?? I think its straight forward.
>
> > If I hv two Stack
> > First :- Keep pushing and Popping the incoming values
> > Second :- Keeping track of the so far min element in the First Stack.
>
> > Now maintaining second stack is bit tricky.
> > PUSH :- If the element is first element Push the Same
> > element in Second Stack what we Pushed in Stack 1.
> > Else compare the last Second.top with Current
> > Element
> > Push which ever
> > is smaller (or Equal).
>
> > POP :- POP both the stack simultaneously.
>
> > On Tue, Sep 6, 2011 at 5:52 PM, Don <[email protected]> wrote:
>
> >> @HARISH:
> >> Push 20 1 3 1 5 1 6 1 2 1
> >> Pop
>
> >> Now in your algorithm min will return 20, even though 1 and 3 and
> >> other smaller numbers are still in the stack.
>
> >> Don
>
> >> On Sep 6, 6:25 am, "HARISH S.C" <[email protected]> wrote:
> >> > Have a separate stack for minimum. While pushing, insert the number in
> >> > minimum stack only if the given number is less that or equal to the
> >> number @
> >> > the top of min stack. While removing, remove the value from min stack
> >> only
> >> > if its equal to the value thats popped.
>
> >> --
> >> You received this message because you are subscribed to the Google Groups
> >> "Algorithm Geeks" group.
> >> To post to this group, send email to [email protected].
> >> To unsubscribe from this group, send email to
> >> [email protected].
> >> For more options, visit this group at
> >>http://groups.google.com/group/algogeeks?hl=en.
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Algorithm Geeks" group.
> > To post to this group, send email to [email protected].
> > To unsubscribe from this group, send email to
> > [email protected].
> > For more options, visit this group at
> >http://groups.google.com/group/algogeeks?hl=en.- Hide quoted text -
>
> - Show quoted text -
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.