-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.h
More file actions
125 lines (113 loc) · 2.9 KB
/
stack.h
File metadata and controls
125 lines (113 loc) · 2.9 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
//
// Created by 陆鹏睿 on 2023/6/2.
//
#ifndef CODE_STACK_H
#define CODE_STACK_H
template <class elemType>
class stack
{
public:
virtual bool isEmpty() const = 0;
virtual void push(const elemType &x) = 0;
virtual elemType pop() = 0;
virtual elemType top() const = 0;
virtual ~stack() {}
};
template <class elemType>
class seqStack: public stack<elemType>
{
private:
elemType *elem;
int top_p=0;
int maxSize;
void doubleSpace();
public:
seqStack(int initSize = 10) ;
~seqStack() { delete [] elem; }
bool isEmpty() const ;
void push(const elemType &x);
elemType pop();
elemType top() const { return elem[top_p]; }
};
template<class elemType>
elemType seqStack<elemType>::pop() {
{ return elem[top_p]; }
}
template <class elemType>
void seqStack<elemType>::push(const elemType &x)
{
if (top_p == maxSize - 1)
doubleSpace();
elem[top_p] = x;
}
template <class elemType>
seqStack<elemType>::seqStack(int initSize) {
elem = new elemType[initSize];
maxSize = initSize ;
top_p = 0;
}template<class elemType>
bool seqStack<elemType>::isEmpty() const {
return top_p==-1;
}
template <class elemType>
void seqStack<elemType>::doubleSpace()
{
elemType *tmp = elem;
elem = new elemType[2 * maxSize];
for (int i = 0; i < maxSize; ++i)
elem[i] = tmp[i];
maxSize *= 2;
delete [] tmp;
}
struct Node {
int data;
Node* next;
};
class Queue {
public:
Node* front; // 队首指针
Node* rear; // 队尾指针
Queue() : front(nullptr), rear(nullptr) {}
~Queue() {
while (front != nullptr) {
Node* temp = front;
front = front->next;
delete temp;
}
}
// 判断队列是否为空
bool isEmpty() {
return (front == nullptr);
}
// 入队
void enqueue(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
// 如果队列为空,新节点既是队首也是队尾
if (isEmpty()) {
front = rear = newNode;
} else {
// 将新节点添加到队尾,并更新队尾指针
rear->next = newNode;
rear = newNode;
}
}
// 出队
void dequeue() {
if (isEmpty()) return;
Node* temp = front; // 保存当前队首节点的指针
front = front->next; // 更新队首指针
// 如果队列只有一个节点,出队后队列为空,需要更新队尾指针
if (front == nullptr) {
rear = nullptr;
}
delete temp; // 释放原队首节点的内存
}
// 获取队首元素
int getFront() {
if (isEmpty()) return -1;
return front->data;
}
};
#endif //CODE_STACK_H