双向栈表
include <stdio.h>
include <stdlib.h>
include <stdbool.h>
define MAXSIZE 100 // 定义数组的最大长度
typedef struct {
int data[MAXSIZE];
int top1; // 第一个栈的栈顶指针
int top2; // 第二个栈的栈顶指针
} DoubleStack;
// 初始化双栈
void initStack(DoubleStack *stack) {
stack->top1 = -1;
stack->top2 = MAXSIZE;
}
// 检查第一个栈是否满
bool isFullStack1(DoubleStack *stack) {
return stack->top1 + 1 == stack->top2;
}
// 检查第一个栈是否为空
bool isEmptyStack1(DoubleStack *stack) {
return stack->top1 == -1;
}
// 检查第二个栈是否满
bool isFullStack2(DoubleStack *stack) {
return stack->top2 - 1 == stack->top1;
}
// 检查第二个栈是否为空
bool isEmptyStack2(DoubleStack *stack) {
return stack->top2 == MAXSIZE;
}
// 向第一个栈压入元素
bool pushStack1(DoubleStack *stack, int value) {
if (isFullStack1(stack)) {
printf("Stack 1 is full!\n");
return false;
}
stack->data[++(stack->top1)] = value;
return true;
}
// 从第一个栈弹出元素
bool popStack1(DoubleStack *stack, int *value) {
if (isEmptyStack1(stack)) {
printf("Stack 1 is empty!\n");
return false;
}
*value = stack->data[(stack->top1)--];
return true;
}
// 向第二个栈压入元素
bool pushStack2(DoubleStack *stack, int value) {
if (isFullStack2(stack)) {
printf("Stack 2 is full!\n");
return false;
}
stack->data[--(stack->top2)] = value;
return true;
}
// 从第二个栈弹出元素
bool popStack2(DoubleStack *stack, int *value) {
if (isEmptyStack2(stack)) {
printf("Stack 2 is empty!\n");
return false;
}
*value = stack->data[(stack->top2)++];
return true;
}
int main() {
DoubleStack stack;
initStack(&stack);
// 测试第一个栈
pushStack1(&stack, 10);
pushStack1(&stack, 20);
int value;
popStack1(&stack, &value);
printf("Popped from Stack 1: %d\n", value);
// 测试第二个栈
pushStack2(&stack, 30);
pushStack2(&stack, 40);
popStack2(&stack, &value);
printf("Popped from Stack 2: %d\n", value);
return 0;
}