顺序栈以及两栈共享空间(C语言版)

本文详细介绍了两种栈的实现方式:顺序栈和双栈共享空间。顺序栈使用固定大小的数组存储元素,提供了初始化、压栈、弹栈和打印栈的操作。双栈共享空间则在同一数组中同时维护两个栈,通过不同的顶部指针实现,避免了空间浪费,同样支持基本的栈操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*01 顺序栈的存储结构*/

Sqstack.h

#define OK 1

#define ERROR 0

#define MAXSIZE 100

typedef int ElemType;

typedef int Status;

typedef struct

{

ElemType data[MAXSIZE];

int top;

}Sqstack;

Status InitStack(Sqstack *S);/*初始化顺序栈*/

Status  Push(Sqstack *S, ElemType e);/*压栈*/

Status Pop(Sqstack *S, ElemType *e);/*弹栈*/

void PrintStack(Sqstack s);/*打印栈中元素*/

 

Sqstack.c

Status InitStack(Sqstack *S)

{

S->top = -1;

return OK;

}

Status  Push(Sqstack *S, ElemType e)

{

if(S->top == MAXSIZE-1)

{

return ERROR;

}

S->top++;

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

return OK;

}

Status Pop(Sqstack *S, ElemType *e)

{

if(S->top == -1)

{

return ERROR;

}

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

S->top--;

return OK;

}

void PrintStack(Sqstack s)

{

while(s->top != -1)

{

printf("%d ", s->data[s->top]);

s->top--;

}

printf("\n");

}

 

/*02 两栈共享空间 存储结构*/

SqDoubleStack.h

#define OK 1

#define ERROR 0

#define MAXSIZE 100

typedef int ElemType;

typedef int Status;

typedef struct

{

ElemType data[MAXSIZE ];

int top1;

int top2;

}SqDoubleStack;

SqDoubleStack.c

Status InitStack(SqDoubleStack *S)

{

S->top1 = -1;

S->top2 = MAXSIZE ;

return OK;

}

Status Push(SqDoubleStack *S, ElemType e, int stackNumber)

{

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

{

return ERROR;

}

if(1 == stackNumber)

{

S->top1++;

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

}

else if(2 == stackNumber)

{

S->top2--;

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

}

else;

return OK;

}

Status  Pop(SqDoubleStack  *S, ElemType *e, int stackNumber)

{

if(1 == stackNumber )

{

if(S->top1 == -1)

{

return ERROR;

}

else

{

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

S->top1--;

}

}

else if(2 == stackNumber )

{

if(S->top2 == MAXSIZE )

{

return ERROR;

}

else

{

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

S->top2++;

}

}

else;

}

void PrintStack(SqDoubleStack  s, int stackNumber)

{

if(stackNumber == 1)

{

while(s.top1 != -1)

{

printf("%d ", s.data[s.top1]);

s.top1--;

}

printf("\n");

}

else if(stackNumber  == 2)

{

while(s.top2 != MAXSIZE)

{

printf("%d ", s.data[s.top2]);

s.top2++;

}

printf("\n");

}

else;

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值