Reverse Elements in Stack (ITERATIVE APPROACH, ONLY EXPLAINATION) !
Assume the stack to be reversed is S1
It can be done using two different stacks (helper stacks)
or by a single helper stack.
A) TWO HELPER STACKS (Let them be S2 and S3)
S1(POP all)-->S2(POP all)-->S3(POP all)-->S1(elements reversed)
B)ONE HELPER STACK (let it be S2)
->
i=0
x=S1.top()
pop top element
pop remaining(n-1-i) elements and push in S2.
Now push x in S1.
and pop S2 completely and push it in S1
i++
(Now initial top most element is at bottom)
-------------------------------------------------
now store top most value in x=S1.top()
pop top element
pop remaining (n-1-i) elements and push in S2.
Now push x in S1.
and pop S2 completely and push it in S1
i++
(Now initial second top most element is at second position from bottom)
----------------------------------------------------------------------------------------
continue until i==n-1
Comments
Post a Comment