两栈共享空间

来源:互联网 发布:分类别思维知乎 编辑:程序博客网 时间:2024/05/01 18:34
#include <stdio.h>#include <malloc.h>#include <stdio.h>#define MAXSIZE 10#define ERROR false#define OK truetypedef int sElemType;typedef struct {sElemType data[MAXSIZE];int top1;//栈顶一int top2;//栈顶二} sqDoubleStack;bool Push(sqDoubleStack* stack, sElemType e, int stackNumber) {if (stack->top1 + 1 == stack->top2) {return ERROR;  //栈以满}if (stackNumber == 1) {stack->top1++;stack->data[stack->top1] = e;} else if (stackNumber == 2) {stack->top2--;stack->data[stack->top2] = e;}return OK;}bool Pop(sqDoubleStack* stack, int stackNumber, sElemType* e) {if (stackNumber == 1) {if (stack->top1 == -1) {return ERROR;//空栈}*e = stack->data[stack->top1];stack->top1--;} else if (stackNumber == 2) {if (stack->top2 == MAXSIZE) {return ERROR;  //空栈}*e = stack->data[stack->top2];stack->top2++;}return OK;}int main() {sqDoubleStack* stack = (sqDoubleStack*) malloc(sizeof(sqDoubleStack));stack->top1 = -1;stack->top2 = MAXSIZE;for (int i = 0; i < 5; i++) {Push(stack, i, 1);}for (int i = 5; i < 10; i++) {Push(stack, i, 2);}sElemType e;//出栈 printf("一号栈\n");for (int i = 0; i < 5; i++) {if (Pop(stack, 1, &e))printf("%d\n", e);}printf("二号栈\n");for (int i = 0; i < 5; i++) {if (Pop(stack, 2, &e))printf("%d\n", e);}return 0;}

0 0
原创粉丝点击