A linked list stack stores each element in a node that contains the data and a pointer to the next node, which uses extra memory. An array stack stores elements in contiguous memory without extra pointers.
class ArrayStack { int *arr; int top; int capacity; public: ArrayStack(int size) { arr = new int[size]; capacity = size; top = -1; } void push(int x) { if (top == capacity - 1) { std::cout << "Stack Overflow\n"; return; } arr[++top] = x; } void print() { for (int i = 0; i <= top; i++) { std::cout << arr[i] << " "; } std::cout << "\n"; } }; int main() { ArrayStack s(3); s.push(10); s.push(20); s.push(30); s.push(40); s.print(); return 0; }
The stack has capacity 3. The fourth push triggers the overflow message and does not add the element. The print shows only the first three elements.
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
class LinkedListStack {
Node* top;
public:
LinkedListStack() : top(nullptr) {}
void push(int x) {
Node* n = new Node(x);
n->next = top;
top = n;
}
int pop() {
if (!top) return -1;
int val = top->data;
Node* temp = top;
top = top->next;
delete temp;
return val;
}
void print() {
Node* curr = top;
while (curr) {
std::cout << curr->data << " ";
curr = curr->next;
}
std::cout << "\n";
}
};
int main() {
LinkedListStack s;
s.push(5);
s.push(10);
s.push(15);
s.pop();
s.push(20);
s.print();
return 0;
}Push 5,10,15 makes stack top=15->10->5. Pop removes 15. Push 20 adds 20 on top. Final stack: 20->10->5.
Both stacks perform push and pop in constant time O(1) on average. Array resizing can cause occasional O(n), but amortized cost is O(1).
A linked list stack grows dynamically without needing resizing or large fixed memory. Array stacks require resizing or large fixed size, which can be inefficient.
