1. Algorithm for PUSH Operation — Linked Stack
Purpose: To insert a new node containing value `val` at the top of a linked stack.
Initial condition:
`top` is a pointer to the topmost node.
If the stack is empty, `top = NULL`.
Algorithm: PUSH
Algorithm PUSH(val)
1. x ← NEWNODE
2. Info(x) ← val
3. Next(x) ← top
4. top ← x
5. Stop
Explanation
Step 1: Create a new node `x`.
Step 2: Store the value `val` in the information field of node `x`.
Step 3: Make `Next(x)` point to the current top node.
Step 4: Move `top` to the newly created node `x`.
Step 5: The insertion is complete.
# 2. Algorithm for POP Operation — Linked Stack
Purpose:To remove and return the topmost node/value from a linked stack.
Underflow condition:
top = NULL
If `top == NULL`, there is no node to delete and therefore Stack Underflow occurs.
Algorithm: POP
Algorithm POP()
1. If top = NULL then
Print "Underflow Error"
Return
2. x ← top
3. top ← Next(top)
4. DelVal ← Info(x)
5. DELETE(x)
6. Return DelVal
7. Stop
Explanation
Step 1: Check whether the stack is empty.
Step 2: Store the address of the current top node in `x`.
Step 3: Move `top` to the next node.
Step 4: Store the value of the deleted node in `DelVal`.
Step 5: Delete/free node `x`.
Step 6: Return the deleted value.
*Step 7:The deletion is complete.
Important Concept
For a linked stack, insertion and deletion are performed only at the `top`.
TOP
↓
Newest Element
↓
Next Node
↓
Next Node
↓
NULL
Therefore, a linked stack follows the **LIFO (Last In, First Out)** principle.