Day 4 - Stacks and Queues
Stacks
Basic Operations

Basic Operations on a Stack

Stack using Arrays

Insert an Element

  • ALGORITHM
Step 1: if top = max - 1
                Write Overflow
                Go to step 4
        [END OF if]
Step 2: SET top = top + 1
Step 3: SET top = val
Step 4: END
  • CODE

Delete an Element

  • ALGORITHM
Step 1: if top = NULL
            Write Underflow
            Go to step 4
        [END OF if]
Step 2: SET val = stack[top]
Step 3: SET top = top - 1
Step 4: EXIT
  • CODE

Peek Operation

  • ALGORITHM
step 1: if top = NULL
            Write Underflow
            Go to step 3
        [END OF if]
step 2: return stack[top]
step 3: EXIT
  • CODE

Stack using Linked List

Insert an Element

  • ALGORITHM
Step 1: Allocate memory for the new node and name it newNode
Step 2: SET newNode->data = val
Step 3: if top = NULL
            SET newNode->next = NULL
            SET top = newNode
        else
            SET newNode->next = top
            SET top = newNode
        [END OF if]
Step 4: END
  • CODE

Delete an Element

  • ALGORITHM
Step 1: if top = NULL
            Write Underflow
            Go to step 5
        [END OF if]
Step 2: SET ptr = top
Step 3: SET top = top->next
Step 4: free ptr
Step 5: EXIT
  • CODE

Peek Operation

  • ALGORITHM
Step 1: if top = NULL
                Write Underflow
                Go to step 3
        [END OF if]
Step 2: return top->data
Step 3: EXIT
  • CODE