Operations on Stacks:
Stacks support various operations, primarily involving adding and removing elements. The fundamental operations on stacks are:
- Push: Adds an element to the top of the stack.
- Pop: Removes and returns the element at the top of the stack.
- Peek (or Top): Returns the element at the top of the stack without removing it.
- isEmpty: Checks if the stack is empty.
- isFull: Checks if the stack is full (in the context of a fixed-size stack).
- Size: Returns the number of elements currently in the stack.
- Clear: Removes all elements from the stack, leaving it empty.
Array Representation of Stack:
In the array representation of a stack, a fixed-size array is typically used to implement the stack. The array has a fixed capacity, and a pointer (often called top
) is used to keep track of the top element of the stack. Here’s how the array representation works:
- The
top
pointer points to the index of the top element in the stack. - When a new element is pushed onto the stack,
top
is incremented, and the element is placed attop
index. - When an element is popped from the stack, the element at
top
index is returned, andtop
is decremented.
Linked Representation of Stack:
In the linked representation of a stack, each element of the stack is represented as a node in a linked list. Each node contains the data element and a pointer to the next node in the stack. The top of the stack is represented by the head of the linked list.
- Push operation involves creating a new node with the data and pointing it to the current top node. Then updating the top pointer to the newly added node.
- Pop operation involves removing the top node from the linked list and updating the top pointer to point to the next node.
- Peek operation returns the data of the top node without removing it.
- isEmpty operation checks if the top pointer is null, indicating an empty stack.
Operations Associated with Stacks:
- Push: Adds an element onto the stack.
- Pop: Removes the top element from the stack.
- Peek (or Top): Returns the top element without removing it.
- isEmpty: Checks if the stack is empty.
- isFull: Checks if the stack is full (for fixed-size stacks).
- Size: Returns the number of elements in the stack.
- Clear: Removes all elements from the stack.
- Traversal: Iterates through the elements of the stack.
- Conversion: Converts infix expressions to postfix or prefix using stacks (used in expression evaluation).
- Undo/Redo: Used in applications like text editors for implementing undo and redo functionality.