-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack_using_linked_list.cpp
More file actions
103 lines (84 loc) · 2.06 KB
/
Copy pathStack_using_linked_list.cpp
File metadata and controls
103 lines (84 loc) · 2.06 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
};
struct Node *top = NULL;
int isEmpty(){
return (top == NULL);
}
struct Node *createNode(int item){
struct Node *ptr;
ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = item;
ptr->next = NULL;
return ptr;
}
void push(int item){
struct Node *ptr = createNode(item);
ptr->next = top;
top = ptr;
}
void pop(){
struct Node *temp = top;
top = top->next;
free(temp);
}
int peek(){
return top->data;
}
void display(){
struct Node *temp = top;
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
return;
}
int main() {
int choice, item;
while (true) {
cout << "\nMenu:\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Peek\n";
cout << "4. Display Stack\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the element to push onto the stack: ";
cin >> item;
push(item);
display();
break;
case 2:
if (isEmpty()) {
cout << "Stack is empty. Cannot perform pop operation!" << endl;
} else {
cout << "Popped element: " << peek() << endl;
pop();
display();
}
break;
case 3:
if (isEmpty()) {
cout << "Stack is empty. Nothing to peek!" << endl;
} else {
cout << "Top element is: " << peek() << endl;
}
break;
case 4:
display();
break;
case 5:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice! Please try again." << endl;
}
}
return 0;
}