-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
98 lines (92 loc) · 2.05 KB
/
stack.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
#ifndef STACK_CPP
#define STACK_CPP
#include <cstddef>
template<typename T>
class Stack {
struct Node {
T value;
Node* next;
};
unsigned int length;
Node* _top;
Node* last;
public:
Stack() {
length = 0;
last = new Node();
last -> next = NULL;
_top = last;
}
Stack(const Stack<T>& other) {
length = 0;
last = new Node();
last -> next = NULL;
_top = last;
Node* cur = other._top;
T* tmp = new T[other.size()];
for(int i=0;cur!=other.last;i++) {
tmp[i] = cur->value;
cur = cur->next;
}
for(int i=other.size()-1;i>=0;i--) push(tmp[i]);
}
void push(T _value) {
Node* tmp = new Node();
tmp -> value = _value;
tmp -> next = _top;
_top = tmp;
length++;
}
void pop() {
if(length == 0) return;
Node* ptop = _top;
_top = _top -> next;
delete ptop;
length--;
}
T top() const {
if(length == 0) return 0;
return _top -> value;
}
unsigned int size() const {
return length;
}
bool empty() const {
return length == 0;
}
class iterator {
Node* curr;
public:
iterator(const iterator& other) {
this->curr = other.curr;
}
iterator(Node* node) {
curr = node;
}
T operator*() {
return curr->value;
}
iterator& operator++() {
curr = curr -> next;
return *this;
}
iterator operator++(int) {
iterator tmp = *this;
curr = curr -> next;
return tmp;
}
bool operator!=(const iterator& other) {
return other.curr != this->curr;
}
bool operator==(const iterator& other) {
return other.curr == this->curr;
}
};
iterator begin() {
return iterator(_top);
}
iterator end() {
return iterator(last);
}
};
#endif