Data Structure (2130702)

BE | Semester-3   Summer-2017 | 05/31/2017

Q3) (b)

Write an algorithm for inserting an element in a stack, removing an element from 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 Stack underflow]
  If TOP = 0
  Then Write (‘STACK UNDERFLOW ON POP’)
    Return(0)
2. [Decrement TOP Pointer]
  TOP ? TOP - 1
3. [Return former top element of stack]
  Return (S[TOP + 1])