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

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree