-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLV_stack03.cpp
104 lines (94 loc) · 1.27 KB
/
LV_stack03.cpp
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
#include <iostream>
using namespace std;
class Node {
private:
int elem;
Node* next;
public:
Node() {
elem = 0;
next = nullptr;
}
~Node() {
elem = 0;
next = nullptr;
}
friend class Stack;
};
class Stack {
public:
bool empty() {
return (head == NULL || tail == NULL);
}
void top() {
if (empty()) {
cout << -1 << endl;
}
else {
Node* cur_node = head;
cout << cur_node->elem << endl;
}
}
void push(int x) {
Node* new_node = new Node;
new_node->elem = x;
if (empty()) {
head = new_node;
tail = new_node;
}
else {
new_node->next = head;
head = new_node;
}
size++;
}
void pop() {
Node* cur_node;
if (empty()) {
cout << -1 << endl;
}
else {
top();
if (size == 1) {
tail = NULL;
head = NULL;
}
else {
cur_node = head;
head = cur_node->next;
}
size--;
}
}
private:
Node* head;
Node* tail;
int size = 0;
};
int main() {
int N;
string str;
Stack sta;
cin >> N;
while (N--) {
cin >> str;
if (str == "empty") {
if (sta.empty() == true) {
cout << 1 << endl;
}
else {
cout << 0 << endl;
}
}
else if (str == "top") {
sta.top();
}
else if (str == "push") {
int x; cin >> x;
sta.push(x);
}
else if (str == "pop") {
sta.pop();
}
}
}