-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.cpp
More file actions
142 lines (119 loc) · 2.35 KB
/
3.cpp
File metadata and controls
142 lines (119 loc) · 2.35 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <iostream>
using namespace std;
class DynamicStack {
private:
int *arr;
int top;
int capacity;
// 扩展栈的容量
void resize() {
capacity *= 2;
int* newArr = new int[capacity];
for (int i = 0; i <= top; ++i) {
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
}
public:
DynamicStack(int cap = 10) : capacity(cap), top(-1) {
arr = new int[capacity];
}
// 进栈
void push(int value) {
if (top == capacity - 1) {
resize();
}
arr[++top] = value;
}
// 出栈
int pop() {
if (top == -1) {
cout << "Stack is empty!" << endl;
return -1;
}
return arr[top--];
}
// 查看栈顶元素
int peek() {
if (top == -1) {
cout << "Stack is empty!" << endl;
return -1;
}
return arr[top];
}
~DynamicStack() {
delete[] arr;
}
};
// 链队列节点定义
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// 链队列类定义
class LinkedQueue {
private:
Node* front;
Node* rear;
public:
LinkedQueue() : front(nullptr), rear(nullptr) {}
// 入队
void enqueue(int value) {
Node* newNode = new Node(value);
if (rear) {
rear->next = newNode;
} else {
front = newNode;
}
rear = newNode;
}
// 出队
int dequeue() {
if (!front) {
cout << "Queue is empty!" << endl;
return -1;
}
int value = front->data;
Node* temp = front;
front = front->next;
if (!front) {
rear = nullptr;
}
delete temp;
return value;
}
// 查看队头元素
int peek() {
if (!front) {
cout << "Queue is empty!" << endl;
return -1;
}
return front->data;
}
~LinkedQueue() {
while (front) {
Node* temp = front;
front = front->next;
delete temp;
}
}
};
int main() {
LinkedQueue queue;
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
cout << "Front of queue: " << queue.peek() << endl;
cout << "Dequeue from queue: " << queue.dequeue() << endl;
cout << "Front of queue after dequeue: " << queue.peek() << endl;
DynamicStack stack;
stack.push(10);
stack.push(20);
stack.push(30);
cout << "Top of stack: " << stack.peek() << endl;
cout << "Pop from stack: " << stack.pop() << endl;
cout << "Top of stack after pop: " << stack.peek() << endl;
return 0;
}