-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
85 lines (73 loc) · 1.56 KB
/
stack.h
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
#pragma once
namespace mystd {
template<typename T>
class stack {
private:
class Node {
friend class stack;
private:
T data;
Node* next;
Node* prev;
public:
Node() :next(nullptr), prev(nullptr) {}
Node(T _data) :Node(_data, nullptr, nullptr) {}
Node(T _data, Node* _next, Node* _prev) :data(_data), next(next), prev(_prev) {}
};
private:
//封装链表,头节点做栈底,尾节点为栈顶
Node* head;
Node* tail;
size_t stackSize;
public:
stack() :head(nullptr), tail(nullptr), stackSize(0) {}
~stack() {
while (head) {
Node* p = head;
head = head->next;
delete p;
}
head = tail = nullptr;
stackSize = 0;
}
size_t size()const noexcept { return stackSize; }
bool empty()const noexcept { return stackSize == 0; }
void push(const T& value) {
if (empty()) {
head = tail = new Node(value);
stackSize++;
return;
}
tail->next = new Node(value, nullptr, tail);
tail = tail->next;
stackSize++;
}
void push(T&& value) {
if (empty()) {
head = tail = new Node(value);
stackSize++;
return;
}
tail->next = new Node(value, nullptr, tail);
tail = tail->next;
stackSize++;
}
void pop() {
stackSize--;
if (empty()) {
delete tail;
tail = head = nullptr;
return;
}
Node* p = tail;
tail = tail->prev;
tail->next = nullptr;
delete p;
}
T& top() {
if (!empty())
return tail->data;
throw std::out_of_range("at top()");
}
};
}