Stack Implementation using Linked List (C++)
A Stack is a linear data structure that follows the LIFO (Last In First Out) principle.
C++ Code:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* top = NULL;
void push(int value) {
Node* newNode = new Node();
if (!newNode) {
cout << "Stack Overflow\n";
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
}
void pop() {
if (top == NULL) {
cout << "Stack Underflow\n";
return;
}
Node* temp = top;
top = top->next;
delete temp;
}
void peek() {
if (top != NULL)
cout << "Top: " << top->data << endl;
}
void display() {
Node* temp = top;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL\n";
}
Key Points:
• Stack follows LIFO
• Top is the head of linked list
• Dynamic size (no overflow unless memory full)
• Push and Pop are O(1) operations
Exam Questions
1 Define a stack and explain LIFO with an example.
2 Implement a stack using a linked list. Write code for push and pop operations.
3 Differentiate between stack implementation using array and linked list.
4 Explain stack overflow and stack underflow.
5 Write an algorithm for push and pop operations in a linked list stack.
6 Trace the output of stack operations: push(10), push(20), pop(), push(30), display().