Data Structure (2130702)

BE | Semester-3   Winter-2015 | 12/15/2015

Q2) (a)

Write an algorithm to implement PUSH and POP Operations on Stack.

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])