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

Linked List Stack Implementation in C++

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)
21 views3 pages

Linked List Stack Implementation in C++

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

#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;
[Link](value);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]();
break;
case 5:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 5);

return 0;
}

You might also like