Data Structure (2130702)

BE | Semester-3   Winter-2014 | 01/01/2015

Q1) (c)

Explain PUSH and POP operation of the stack with algorithm.

Procedure: PUSH (S, TOP, X)

  • This procedure inserts an element X to the top of a stack.
  • Stack is represented by a vector S containing N elements.
  • A pointer TOP represents the top element in the stack.
1.[Check for stack overflow]
 If TOP ≥ N
 Then write (‘STACK OVERFLOW’)
  Return
2. [Increment TOP]
 TOP ←TOP + 1
3. [Insert Element]
 S[TOP] ←X
4. [Finished]
 Return

Function: POP (S, TOP)

  • This function removes & returns the top element from a stack.
  • Stack is represented by a vector S containing N elements.
  • A pointer TOP represents the top element in the stack.
1. [Check for underflow of stack]
 If TOP = 0
 Then Write (‘STACK UNDERFLOW ON POP’)
  Take action in response to underflow
  Return
2. [Decrement Pointer]
 TOP ← TOP – 1
3. [Return former top element of stack]
 Return (S[TOP + 1])