Algorithm:: Start The Program. Define Node Structure
Algorithm:: Start The Program. Define Node Structure
Algorithm:
1. Start the program.
2. Define Node Structure:
• Create a class Node with two members:
• data: stores the value.
• next: a pointer to the next node.
3. Define Stack Class:
• Create a class Stack with the following members:
• top: a pointer to the top of the stack.
• Include the following operations in the class:
Source code:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = NULL;
}
};
class Stack {
private:
Node* top;
public:
Stack() {
top = NULL;
}
void pop() {
if (top == NULL) {
cout << "Stack is empty. Cannot pop.\n";
return;
}
Node* temp = top;
top = top->next;
cout << "Popped " << temp->data << " from the stack.\n";
delete temp;
}
void peek() {
if (top == NULL) {
cout << "Stack is empty.\n";
return;
}
cout << "Top element: " << top->data << endl;
}
bool isEmpty() {
return top == NULL;
}
void display() {
if (top == NULL) {
cout << "Stack is empty.\n";
return;
}
Node* temp = top;
cout << "Stack elements: ";
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Stack stack;
int choice, value;
while (true) {
cout << "\n--- Stack Menu ---\n";
cout << " 1.Push--";
cout << " 2.Pop--";
cout << " 3.Peek--";
cout << " 4.Display--";
cout << " 5.Exit--\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
stack.push(value);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice. Try again.\n";
}
}
}
Output:
Conclusion:
This C++ program demonstrates the implementation of stack operations using
a linked list. It provides the fundamental stack operations such as push, pop,
peek, and display, along with checking if the stack is empty. By using a linked
list, the stack is dynamic, meaning it can grow and shrink as needed without
being constrained by a fixed size, unlike array-based stacks.
This linked-list-based approach offers flexibility and avoids issues like stack
overflow that may occur with an array-based stack when the array is of limited
size.