print linkedstack cpp
include
using namespace std;
class Node { public: int data; Node* next; };
class LinkedStack { private: Node* top; public: LinkedStack() { top = NULL; }
void push(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
}
void pop() {
if (top == NULL) {
cout << "Stack is empty." << endl;
} else {
Node* temp = top;
top = top->next;
delete temp;
}
}
int peek() {
if (top == NULL) {
cout << "Stack is empty." << endl;
return -1;
} else {
return top->data;
}
}
bool isEmpty() {
return top == NULL;
}
};
int main() { LinkedStack stack; stack.push(10); stack.push(20); stack.push(30); stack.push(40);
cout << "Top element: " << stack.peek() << endl;
stack.pop();
stack.pop();
cout << "Top element after popping twice: " << stack.peek() << endl;
if (stack.isEmpty()) {
cout << "Stack is empty." << endl;
} else {
cout << "Stack is not empty." << endl;
}
return 0;
}