#include <iostream.
h>
// Node structure
struct Node {
int data;
Node* next;
};
// Stack class using linked list
class Stack {
private:
Node* top; // pointer to top element
public:
Stack() {
top = nullptr;
}
// Push operation
void push(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
cout << value << " pushed into stack.\n";
}
// Pop operation
void pop() {
if (top == nullptr) {
cout << "Stack Underflow! Cannot pop.\n";
return;
}
cout << top->data << " popped from stack.\n";
Node* temp = top;
top = top->next;
delete temp;
}
// Peek operation
void peek() {
if (top == nullptr) {
cout << "Stack is empty.\n";
return;
}
cout << "Top element is: " << top->data << endl;
}
// Display operation
void display() {
if (top == nullptr) {
cout << "Stack is empty.\n";
return;
}
Node* temp = top;
cout << "Stack elements: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
// Main function
int main() {
Stack s;
int choice, value;
do {
cout << "\n--- Stack Menu ---\n";
cout << "1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
s.push(value);
break;
case 2:
s.pop();
break;
case 3:
s.peek();
break;
case 4:
s.display();
break;
case 5:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 5);
return 0;
}