数据结构共享栈C语言算法代码,数据结构之---C语言实现共享栈

所谓共享栈是两个栈在一个顺序的存储空间中。两个栈的栈底各自是存储空间的首尾地址。

如图我们能够将两个栈构造成一个:

如图:

2fb40edf78f46b948e2246554d45529e.png

从这里也就能够分析出来,栈1为空时,就是top1等于-1时。而当top2等于n时,即是栈2为空时,那么什么时候栈满呢?

想想极端的情况,若栈2是空栈,栈1的top1等于n-1时,就是栈1满了。反之,当栈1为空栈时。top2等于0时,为栈2满。

但很多其它的情况,事实上就是刚才说的,两个栈见面之时,也就是两个指针之间相差1时。即top1+1==top2为栈满。

详细的实现代码例如以下:

//共享栈

//杨鑫

#include

#include

#define MaxSize 60

#define OK 1

#define ERROR 0

#define TRUE 1

#define FALSE 0

typedef int ElemType;

typedef int Status;

typedef struct {

ElemType data[MaxSize];

int top1;

int top2;

}Stack, *pStack;

Status init_Stack(pStack S)

{

S->top1 = -1;

S->top2 = MaxSize;

return OK;

}

Status push_Stack(pStack S, ElemType e, int stackNumber)

{

if (S->top1+1 == S->top2)

return ERROR;

switch(stackNumber)

{

case 1:

S->data[++S->top1] = e;

break;

case 2:

S->data[--S->top2] = e;

break;

}

return OK;

}

Status pop_Stack(pStack S, ElemType *e, int stackNumber)

{

if (1 == stackNumber)

{

if (-1 == S->top1)

return ERROR;

*e = S->data[S->top1--];

}

else if (2 == stackNumber)

{

if (MaxSize == S->top2)

return ERROR;

*e = S->data[S->top2++];

}

return OK;

}

Status dis_pStack(pStack S, int stackNumber)

{

int i;

if (1 == stackNumber)

{

if (-1 == S->top1)

return ERROR;

printf("栈1中的元素为:

");

for (i=0; i<=S->top1; ++i)

printf("%d ", S->data[i]);

printf("

==================================

");

}

else if (2 == stackNumber)

{

if (MaxSize == S->top2)

return ERROR;

printf("栈2中的元素为:

");

for (i=MaxSize-1; i>=S->top2; --i)

printf("%d ", S->data[i]);

printf("

==================================

");

}

}

int main()

{

printf("======共享栈===========

");

Stack S;

ElemType e;

init_Stack(&S);

push_Stack(&S, 1, 1);

push_Stack(&S, 2, 1);

push_Stack(&S, 3, 1);

push_Stack(&S, 4, 1);

push_Stack(&S, 5, 1);

push_Stack(&S, 6, 1);

pop_Stack(&S, &e, 1);

push_Stack(&S, 10, 2);

push_Stack(&S, 9, 2);

push_Stack(&S, 8, 2);

push_Stack(&S, 7, 2);

dis_pStack(&S, 1);

dis_pStack(&S, 2);

return 0;

}

图片:

8349f7aa276ab546e04a865379ac4933.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值