Stack Implementation Using Linked List
Stack
with array
implementation has size
limitation.
To make the stack
dynamically grow, we can implement it using linked list
.
Worst case
- Removing a
node
from the end of the list would require us to transverse the whole list fromhead
to thenode
beforecurrent
.
Best case
nodes
can be added at the start usinghead
.nodes
can be added at the end usingcurrent
.
pop()
int value = head->get();
Node* p = head;
head = head->getNext();
delete p;
return value;
int pop () {
int value = head->get();
Node* p = head;
head = head->getNext();
delete p;
return value;
}
push()
Node* newNode = new Node();
newNode->set(value);
newNode->setNext(head);
head = newNode;
void push(int value) {
Node* newNode = new Node();
newNode->set(value);
newNode->setNext(head);
head = newNode;
}
Other methods:
int top () {
return head->get();
}
int isEmpty () {
return (head == NULL);
}
isFULL() is not required since there is no issue of limitations on the stack size
.
Preference
- Linked list: each
stack
element has a higher memory space requirement (for thenext
pointers). The allocation and de-allocation ofnodes
also takes a little bit of time. But the benefit here is the memory can grow and shrink dynamically without any upper limit. - Array: it is pre-allocated so it is faster in terms of
pop()
andpush()
requests. The down side here is the fixed memory space, it cannot grow neither shrink and leaves vacant space behind afterpop()
operations.
Operation Types
1. Infix
When the operator is in between the operands
.
Example: A + B;
2. Prefix
when the operator is before the operands
.
Example: + A B; ++x;
3. Postfix
when the operator is after the operands
.
Example: A B +; x++;
Conversion of Infix to Postfix
Examples: 1. A + (B * C) 1. A + (B C *) 2. A B C * + 2. (A + B) * C 1. (A B +) * C 2. A B + C *
Operator Precedence
- Exponentiation: ^
- Multiplication / Division: *, /
- Addition / Subtraction: +, -
Rules
- A + B + C means (A + B) + C (left-to-right rule).
- A ^ B ^ C means A ^ (B ^ C) (right-to-left rule).
Examples:
infix | postfix |
---|---|
A + B | A B + |
12 + 60 - 23 | 12 60 + 23 - |
(A + B) * (C - D) | A B + C D - * |
A ^ B * C - D + E / F | A B ^ C * D - E F / + |