Array and Linked Implementation of Stack in C
In C, an array stack uses a fixed array and top index (fixed size, no pointer overhead). A linked stack uses dynamic nodes and a top pointer (grows dynamically, extra pointer space). Both push and pop run in O(1) time.
Theory & Explanation
Linked Implementation of Stack (with C & Python Programs)
1. Introduction & Why Linked Stack?
A stack is a linear data structure following the LIFO (Last-In, First-Out) principle: the last element inserted is the first one removed. In an array-based stack, memory size is fixed beforehand (MAX), which can cause Stack Overflow even when free system memory is available, or waste space when only a few elements are stored.
A linked implementation of a stack solves this by storing elements in dynamically allocated nodes connected via pointers. Each node holds two parts:
- Data field: Stores the actual value/element.
- Next pointer: Stores the address of the next node below it in the stack.
A pointer named top (or head) points to the topmost node of the stack. When the stack is empty, top is NULL (in C) or None (in Python). Inserting and deleting at the beginning (head) of a singly linked list gives O(1) time for both Push and Pop without shifting any elements.
2. Node Structure & Stack Representation
In C, a stack node is typically defined using a self-referential struct:
struct Node {
int data;
struct Node next;
};
struct Node top = NULL; // Initially empty stack
Visually, if we push 10, then 20, then 30:
top → [30 | next] → [20 | next] → [10 | NULL]. Here, 30 is at the top and 10 is at the bottom of the stack.
3. Primitive & Supporting Operations (Algorithms)
A. PUSH (Insert at Top)
- Allocate memory for a new node (e.g., using
mallocin C). - If memory allocation fails (
newNode == NULL), report Stack Overflow / Heap Full and return. - Set
newNode->data = value. - Link the new node to the current top:
newNode->next = top. - Update
top = newNode.
B. POP (Remove from Top)
- Check if
top == NULL. If true, report Stack Underflow and return. - Store a temporary pointer
temp = topand savepoppedValue = top->data. - Move
topto the next node:top = top->next. - Free
temp(free(temp)in C) to prevent memory leaks. - Return
poppedValue.
C. PEEK / TOP & DISPLAY
- Peek / Top: If
top == NULL, stack is empty; otherwise returntop->datawithout removing it. - Display / Traverse: Start a traversal pointer
ptr = topand printptr->datawhile advancingptr = ptr->nextuntilNULL.
4. Step-by-Step Trace Example
Starting with top = NULL:
| Operation | Action Taken | Stack from Top to Bottom | Result / Output |
|---|---|---|---|
| Initial | top = NULL |
Empty (NULL) |
Stack is empty |
push(10) |
Node 10 created; 10->next = NULL; top points to 10 |
10 -> NULL |
Pushed 10 |
push(20) |
Node 20 created; 20->next = 10; top points to 20 |
20 -> 10 -> NULL |
Pushed 20 |
push(30) |
Node 30 created; 30->next = 20; top points to 30 |
30 -> 20 -> 10 -> NULL |
Pushed 30 |
peek() |
Reads top->data without modifying pointers |
30 -> 20 -> 10 -> NULL |
Top element is 30 |
pop() |
Saves 30, sets top = 20, frees node 30 |
20 -> 10 -> NULL |
Popped 30 |
pop() |
Saves 20, sets top = 10, frees node 20 |
10 -> NULL |
Popped 20 |
pop() |
Saves 10, sets top = NULL, frees node 10 |
Empty (NULL) |
Popped 10 |
pop() |
top == NULL |
Empty (NULL) |
Stack Underflow |
5. Complexity & Array vs. Linked List Comparison
- Time Complexity:
Push=O(1),Pop=O(1),Peek=O(1),Display=O(n). - Space Complexity:
O(n)fornelements, with extra memory per node for storing the pointer. - Key Advantage over Array Stack: Dynamic size (grows/shrinks at runtime until system memory is exhausted).
- Key Trade-off: Extra pointer overhead per element, non-contiguous memory (less cache-friendly than arrays), and manual memory management (
malloc/free) in C.
6. C Program: Linked Implementation of Stack
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node next;
};
struct Node top = NULL;
void push(int value) {
struct Node newNode = (struct Node )malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack Overflow! Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("Pushed %d\n", value);
}
int pop() {
if (top == NULL) {
printf("Stack Underflow! Stack is empty.\n");
return -1;
}
struct Node temp = top;
int poppedValue = temp->data;
top = top->next;
free(temp);
printf("Popped %d\n", poppedValue);
return poppedValue;
}
void peek() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
printf("Top element: %d\n", top->data);
}
void display() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
struct Node temp = top;
printf("Stack (Top to Bottom): ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
push(10);
push(20);
push(30);
display();
peek();
pop();
display();
pop();
pop();
pop(); // Underflow
return 0;
}
Expected Output (C):
Pushed 10
Pushed 20
Pushed 30
Stack (Top to Bottom): 30 -> 20 -> 10 -> NULL
Top element: 30
Popped 30
Stack (Top to Bottom): 20 -> 10 -> NULL
Popped 20
Popped 10
Stack Underflow! Stack is empty.
7. Python Program: Linked Implementation of Stack
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedStack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, value):
new_node = Node(value)
new_node.next = self.top
self.top = new_node
print(f"Pushed {value}")
def pop(self):
if self.is_empty():
print("Stack Underflow! Stack is empty.")
return None
popped_value = self.top.data
self.top = self.top.next
print(f"Popped {popped_value}")
return popped_value
def peek(self):
if self.is_empty():
print("Stack is empty.")
return None
print(f"Top element: {self.top.data}")
return self.top.data
def display(self):
if self.is_empty():
print("Stack is empty.")
return
temp = self.top
items = []
while temp is not None:
items.append(str(temp.data))
temp = temp.next
print("Stack (Top to Bottom): " + " -> ".join(items) + " -> None")
if __name__ == "__main__":
s = LinkedStack()
s.push(10)
s.push(20)
s.push(30)
s.display()
s.peek()
s.pop()
s.display()
s.pop()
s.pop()
s.pop() # Underflow
Expected Output (Python):
Pushed 10
Pushed 20
Pushed 30
Stack (Top to Bottom): 30 -> 20 -> 10 -> None
Top element: 30
Popped 30
Stack (Top to Bottom): 20 -> 10 -> None
Popped 20
Popped 10
Stack Underflow! Stack is empty.
