数据结构栈和队列代码和注释
时间: 2023-11-08 09:06:59 浏览: 105
以下是数据结构中栈和队列的代码和注释:
<<栈代码>>
```cpp
#define MAXSIZE 100 // 定义栈的最大长度
typedef struct {
int data[MAXSIZE]; // 存放栈中元素
int top; // 栈顶指针
} SqStack; // 顺序栈
// 初始化栈
void InitStack(SqStack &S) {
S.top = -1; // 初始化栈顶指针
}
// 判断栈是否为空
bool StackEmpty(SqStack S) {
if (S.top == -1) {
return true;
} else {
return false;
}
}
// 进栈
bool Push(SqStack &S, int x) {
if (S.top == MAXSIZE - 1) { // 栈满
return false;
}
S.top++; // 栈顶指针加1
S.data[S.top] = x; // 将元素x放入栈顶
return true;
}
// 出栈
bool Pop(SqStack &S, int &x) {
if (S.top == -1) { // 栈空
return false;
}
x = S.data[S.top]; // 将栈顶元素赋值给x
S.top--; // 栈顶指针减1
return true;
}
// 取栈顶元素
bool GetTop(SqStack S, int &x) {
if (S.top == -1) { // 栈空
return false;
}
x = S.data[S.top]; // 将栈顶元素赋值给x
return true;
}
```
<<队列代码>>
```cpp
#define MAXSIZE 100 // 定义队列的最大长度
typedef struct {
int data[MAXSIZE]; // 存放队列中元素
int front; // 队头指针
int rear; // 队尾指针
} SqQueue; // 顺序队列
// 初始化队列
void InitQueue(SqQueue &Q) {
Q.front = Q.rear = 0; // 初始化队头和队尾指针
}
// 判断队列是否为空
bool QueueEmpty(SqQueue Q) {
if (Q.front == Q.rear) {
return true;
} else {
return false;
}
}
// 进队列
bool EnQueue(SqQueue &Q, int x) {
if ((Q.rear + 1) % MAXSIZE == Q.front) { // 队满
return false;
}
Q.data[Q.rear] = x; // 将元素x放入队尾
Q.rear = (Q.rear + 1) % MAXSIZE; // 队尾指针加1
return true;
}
// 出队列
bool DeQueue(SqQueue &Q, int &x) {
if (Q.front == Q.rear) { // 队空
return false;
}
x = Q.data[Q.front]; // 将队头元素赋值给x
Q.front = (Q.front + 1) % MAXSIZE; // 队头指针加1
return true;
}
// 取队头元素
bool GetHead(SqQueue Q, int &x) {
if (Q.front == Q.rear) { // 队空
return false;
}
x = Q.data[Q.front]; // 将队头元素赋值给x
return true;
}
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)