Algorithm
Stack Implementation (Using Linked List):
- Define a Node structure with two fields:
data
: To store the value of the node.next
: To store the reference to the next node.
- Initialize a pointer
top
tonull
to represent the top of the stack. - Define the following operations:
- Push: Add an element to the stack.
- Create a new node and set its
data
to the element to be added. - Set the
next
of the new node to the currenttop
. - Update
top
to point to the new node.
- Create a new node and set its
- Pop: Remove the top element from the stack.
- Check if the stack is empty. If
top == null
, display an underflow error. - Otherwise, store the
data
of the currenttop
node. - Update
top
to point totop.next
. - Delete the old top node and return the stored data.
- Check if the stack is empty. If
- Peek: Retrieve the top element without removing it.
- Check if the stack is empty. If
top == null
, display an error. - Otherwise, return the
data
of thetop
node.
- Check if the stack is empty. If
- IsEmpty: Check if the stack is empty by verifying if
top == null
.
- Push: Add an element to the stack.
Example:
Consider a stack implemented using a linked list. Perform the following operations:
- Push 10, 20, 30
- Pop an element
- Peek the top element
After these operations, the stack will contain [10, 20], and the top element will be 20.