stack using linked list
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Stack {
Node* top;
public:
Stack() { top = NULL; }
void push(int val) {
Node* newNode = new Node();
newNode->data = val;
newNode->next = top;
top = newNode;
cout << val << " pushed to stack.\n";
}
void pop() {
if (top == NULL)
cout << "Stack Underflow!\n";
else {
cout << top->data << " popped from stack.\n";
Node* temp = top;
top = top->next;
delete temp;
}
}
void display() {
cout << "Stack: ";
Node* temp = top;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Stack s;
s.push(5);
s.push(10);
s.display();
s.pop();
s.display();
cout << "\nTime Complexity: O(1)\nSpace Complexity: O(n)\n";
return 0;
}
Editor is loading...
Leave a Comment