Algorithm for user choice:
1. ch=0 // Initialize a variable for user choice
2. Read ch //Enter, user choice 1 for push and 2 for pop
3. If(ch == 1) then /* if top is at end of stack-array */
4. call push function
5. Else
6. call pop function
7. End
Algorithm for pushing in stack-array:
* Assuming that array-stack can hold maximum N elements*/
1. top=-1 /* Initialize stack with invalid subscript value to show that it is empty. Legal subscript values are 0..... (N-1) */
2. Read Item //Item, which is to be pushed
3. If(top== N-1) then /* if top is at end of stack-array */
4. { print "Overflow !!"
}
5. Else
6. { top = top+1 /* Increment top to move to next empty position to hold new item*/
7. Stack[top]=Item }
8. END.
Algorithm for popping in stack-array:
/* Firstly, check for underflow condition */
1. If top==-1 then
{
2. Print "Underflow!!"
3. Exit from program
}
4. Else
{
5. print stack(top)
6. top=top-1 /* top moved, so that the top most element becomes inaccessible which is a sort of a deletion */ }
7. END
Note: We have to shift elements to the right for insertion and left for removal of an element. We face the same problem while implementing the list with the use of the array. If we push and pop the elements from the start of the array for stack implementation, this problem will arise. In case of push, we have to shift the stack elements to the right. However, in case of pop, after removing the element, we have to shift the elements of stack that are in the array to the left. If we push the element at the end of the array, there is no need to shift any element. Similarly as the pop method removes the last element of the stack which is at the end of the array, no element is shifted. To insert and remove elements at the end of the array we need not to shift its elements. Best case for insert and delete is at the end of the array where there is no need to shift any element. We should implement push() and pop() by inserting and deleting at the end of an array.