Stack
Element deleted from the set is the one most recently inserted;
Stack implements last-in, first out or LIFO policy
You can use array to implement Stack
supported operations
insert, delete, empty, top, size
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 | template<typename T>
class Stack {
public:
struct Node {
T val;
Node *next;
Node() {};
Node(T val) : val(val), next(0){};
};
Node *head;
int _size;
Stack() {
head = 0;
_size = 0;
}
void push(T val) {
Node* temp = new Node(val);
if (head == 0) {
head = temp;
} else {
temp->next = head;
head = temp;
}
_size++;
}
void pop() {
if (empty()) return;
Node* temp = head;
head = head->next;
delete temp;
_size--;
}
bool empty() const {
return _size == 0;
}
T top() const {
return head->val;
}
int size() const {
return _size;
}
};
|