双栈初始化,判断栈空,栈满,出栈用代码实现
时间: 2023-05-12 17:06:20 浏览: 175
双栈的建立、判断栈空、栈满、插入和删除操作
双栈初始化、判断栈空、栈满、出栈的代码实现如下:
```c
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top1; // 栈1的栈顶指针
int top2; // 栈2的栈顶指针
} DoubleStack;
// 双栈初始化
void InitDoubleStack(DoubleStack *S) {
S->top1 = -1;
S->top2 = MAXSIZE;
}
// 判断栈1是否为空
int IsEmpty1(DoubleStack *S) {
return S->top1 == -1;
}
// 判断栈2是否为空
int IsEmpty2(DoubleStack *S) {
return S->top2 == MAXSIZE;
}
// 判断栈1是否已满
int IsFull1(DoubleStack *S) {
return S->top1 + 1 == S->top2;
}
// 判断栈2是否已满
int IsFull2(DoubleStack *S) {
return S->top2 - 1 == S->top1;
}
// 入栈1
void Push1(DoubleStack *S, int x) {
if (IsFull1(S)) {
printf("Stack1 is full.\n");
return;
}
S->data[++S->top1] = x;
}
// 入栈2
void Push2(DoubleStack *S, int x) {
if (IsFull2(S)) {
printf("Stack2 is full.\n");
return;
}
S->data[--S->top2] = x;
}
// 出栈1
int Pop1(DoubleStack *S) {
if (IsEmpty1(S)) {
printf("Stack1 is empty.\n");
return -1;
}
return S->data[S->top1--];
}
// 出栈2
int Pop2(DoubleStack *S) {
if (IsEmpty2(S)) {
printf("Stack2 is empty.\n");
return -1;
}
return S->data[S->top2++];
}
```
注意:以上代码仅供参考,可能存在错误或不足之处,使用时请自行斟酌。
阅读全文