Repository navigation
Expand file tree
/
Copy pathstack.cpp
More file actions
105 lines (88 loc) · 1.56 KB
/
Copy pathstack.cpp
File metadata and controls
105 lines (88 loc) · 1.56 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
104
105
#include <bits/stdc++.h>
using namespace std;
typedef struct Node {
int data;
Node* next;
} Node;
class Stack {
Node* top;
public:
Stack() {
top = NULL;
}
Node* createNewNode(int n);
void push(int num);
int pop();
void printStack();
};
// Functions of Stack class
Node* Stack::createNewNode(int n) {
Node* newNode = new Node;
if (newNode) {
newNode->data = n;
newNode->next = NULL;
}
return newNode;
}
void Stack::push(int num) {
Node* node = createNewNode(num);
if (!node) {
cout << "Couldn't create a new node!" << endl;
return;
}
if (top) {
node->next = top;
}
top = node;
}
int Stack::pop() {
if (!top) {
cout << "Couldn't remove node from an empty stack!" << endl;
return -1;
}
Node* temp = top;
top = top->next;
int num = temp->data;
delete temp;
return num;
}
void Stack::printStack() {
cout << "Stack: TOP";
Node* temp = top;
while (temp) {
cout << " -> " << temp->data;
temp = temp->next;
}
cout << " -> NULL" << endl;
}
main(void) {
Stack stack;
int ch, num;
do {
cout << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Exit" << endl;
cout << endl << "Enter your choice: ";
cin >> ch;
cout << endl;
switch (ch) {
case 1:
cout << "Enter number to push: ";
cin >> num;
stack.push(num);
stack.printStack();
break;
case 2:
num = stack.pop();
if (num != -1)
cout << num << " was popped!" << endl;
stack.printStack();
break;
case 3:
break;
default:
cout << "You entered an incorrect choice!" << endl;
}
} while (ch != 3);
}