0% found this document useful (0 votes)
13 views3 pages

C++ 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

C++ 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#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;
}

You might also like