push and pop operation of stack with algorithm

A stack is a Linear Abstract Data Type (ADT) that follows the LIFO(Last in first out) property.

There are two operation which can be performed on stack

1). PUSH

2). POP

PUSH operation of Stack

PUSH operation of the stack is used to add an item to a stack at the top. We can perform Push operation only at the top of the stack. However, before inserting an item in the stack we must check stack should have some empty space.

Push operation can be performed in the below steps

Step 1 Checks stack has some space or stack is full.

Step 2 − If the stack has no space then display “overflow” and exit.

Step 3 − If the stack has space then increase top by 1 to point next empty space.

Step 4 − Adds item to the newly stack location, where top is pointing.

Step 5 – PUSH operation performed successfully.

PUSH Operation Algorithm of Stack

if TOP = MAX-1
       return "Overflow"
 endif
    top = top + 1
    stack[top] = item
 end

Code Snippet of PUSH Operation

public void push(int x)
    {
        if (top >= (MAX - 1)) {
            System.out.println("Stack Overflow");
        }
        else {
            a[++top] = x;
            System.out.println("Item pushed into stack = "+x);
        }
    }

POP Operation of Stack

POP operation is performed on the stack to remove items from the stack. We can perform the Pop operation only at the top of the stack. In an array implementation of pop() operation, the data element is not actually removed, instead the top is decremented to a lower position in the stack to point to the next value.

POP operation can be performed in the below steps

Step 1 − Checks stack has some element or stack is empty.

Step 2 − If the stack has no element means it is empty then display “underflow”

Step 3 − If the stack has element some element, accesses the data element at which top is pointing.

Step 4 − Decreases the value of top by 1.

Step 5 − POP operation performed successfully.

POP Operation Algorithm of Stack

If TOP=-1
       return "Underflow"
 endif
    item=Stack[Top]
     top=top-1
     return Item
 end

Code Snippet of POP Operation

public int pop()
    {
        if (top < 0) {
            System.out.println("Stack Underflow");
            return 0;
        }
        else {
            int x = a[top--];
            return x;
        }
    }

[wpusb]