-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack_Linked_list.cpp
More file actions
77 lines (69 loc) · 1.68 KB
/
Copy pathStack_Linked_list.cpp
File metadata and controls
77 lines (69 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
using namespace std;
// Define a Node structure for the linked list
struct Node {
int data;
Node* next;
};
// Initialize the top of the stack
Node* top = nullptr;
// Push operation: Add an element to the top of the stack
void push(int val) {
Node* newnode = new Node;
newnode->data = val;
newnode->next = top;
top = newnode;
}
// Pop operation: Remove the top element from the stack
void pop() {
if (top == nullptr)
cout << "Stack Underflow" << endl;
else {
cout << "Popped element: " << top->data << endl;
top = top->next;
}
}
// Display the elements in the stack
void display() {
Node* ptr = top;
if (ptr == nullptr)
cout << "Stack is empty" << endl;
else {
cout << "Stack elements: ";
while (ptr != nullptr) {
cout << ptr->data << " ";
ptr = ptr->next;
}
cout << endl;
}
}
int main() {
int choice, val;
cout << "1) Push into stack" << endl;
cout << "2) Pop from stack" << endl;
cout << "3) Display stack" << endl;
cout << "4) Exit" << endl;
do {
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> val;
push(val);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice" << endl;
}
} while (choice != 4);
return 0;
}