Implement stack data structure and its operations using singly linked lists.
Implement stack data structure and its operations using singly linked lists.
#include <iostream>
using namespace std;
class Node {
public:
int data; // Data stored in the node
Node* next; // Pointer to the next node
// Constructor
Node(int value) {
data = value;
next = nullptr;
}
};
class Stack {
private:
Node* top; // Pointer to the top node of the stack
public:
// Constructor
Stack() {
top = nullptr;
}
bool isEmpty() {
return (top == nullptr);
}
void push(int value) {
Node* newNode = new Node(value);
newNode->next = top;
top = newNode;
cout << "Pushed element: " << value << endl;
}
void pop() {
if (isEmpty()) {
cout << "Stack Underflow: Cannot pop element. Stack is empty." << endl;
return;
}
Node* temp = top;
int poppedElement = top->data;
top = top->next;
delete temp;
cout << "Popped element: " << poppedElement << endl;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return top->data;
}
void display() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return;
}
cout << "Stack elements: ";
Node* current = top;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
Stack stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.display();
cout << "Top element: " << stack.peek() << endl;
stack.pop();
stack.display();
stack.pop();
stack.pop();
stack.display();
return 0;
}
Comments
Post a Comment