stack.png利用栈底为止相对不变的特性,可让两个顺序栈共享一个一维数组空间,将两个栈的栈底分别设置在共享空间的两端,两个栈顶向共享空间的中间延伸。
//
// sharestack.c
// Ccode
//
// Created by XX on 2020/4/8.
// Copyright © 2020 XX. All rights reserved.
//
#include "sharestack.h"
#include <stdlib.h>
#define MAX
#define MaxSize 5//定义栈中元素的最大个数
typedef int ElemType;
typedef struct shareStack {
ElemType data[MaxSize];
int top0;
int top1;
}shareStack, *pshare;
pshare CreateShare() {
pshare p = (shareStack *)malloc(sizeof(shareStack));
p->top0 = -1;
p->top1 = MaxSize;
return p;
}
//判空
int EmptyShare(pshare p) {
if (p->top0 == -1 && p->top1 == MaxSize) {
return 0;
}
return -1;
}
//入栈
int PushShare(pshare p, ElemType data, int stackNum) {
if (p == NULL) {
exit(-1);
}
if (p->top0 + 1 == p->top1) {
printf("栈满...\n");
return 0;
}
switch (stackNum) {
case 0:
p->top0 ++;
p->data[p->top0] = data;
return 0;
case 1:
p->top1 --;
p->data[p->top1] = data;
return 0;
default:
return -1;
}
}
//出栈
int PopShare(pshare p, int stackNum) {
int data;
if (p == NULL) {
exit(-1);
}
if (p->top0 == -1 && p->top1 == MaxSize) {
return -1;
}
switch (stackNum) {
case 0:
data = p->data[p->top0];
p->top0 --;
return data;
case 1:
data = p->data[p->top1];
p->top1 ++;
return data;
default:
return -1;
}
}
void testshare() {
int data;
shareStack s;
pshare top = &s;
top = CreateShare();
PushShare(top, 23, 0);
PushShare(top, 23, 0);
PushShare(top, 78, 0);
PushShare(top, 23, 1);
PushShare(top, 45, 1);
PushShare(top, 34, 0);
data = PopShare(top, 0);
printf("%d\n", data);
}
网友评论