# 链式栈基本操作的实现

26 篇文章 0 订阅

#include<stdio.h>
#include<stdlib.h>

#define OK 1
#define ERROR 0

typedef int ElemType, Status;

typedef struct LNode    //栈元素节点
{
ElemType data;    //数据
struct LNode* next;    //指向下一个节点

{
S = (LNode*)malloc(sizeof(LNode));
if (S == NULL) exit(0);
S->next = NULL;
return OK;
}

{
LNode* p = S;
LNode* q = p;
while (p)
{
q = p;
p = p->next;
free(q);
}
free(q);
return OK;
}

{
if (S->next == NULL) return OK;
LNode* p = S->next;
LNode* q;
while (p)
{
q = p;
p = p->next;
free(q);
}
S->next = NULL;
return OK;
}

{
if (S->next == NULL) return OK;
return ERROR;
}

{
LNode* p = S;
int i = 0;
while (p->next)
{
i++;
p = p->next;
}
return i;
}

Status GetTop(LinkStack S, ElemType &e)    //链式栈获取栈顶元素
{
if (S->next == NULL) return ERROR;
e = S->next->data;
return OK;
}

{
if (S->next == NULL) return ERROR;
LNode* p = S->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return OK;
}

Status Push(LinkStack& S, ElemType e)    //链式栈进栈
{
LNode* p = (LNode*)malloc(sizeof(LNode));
if (p == NULL) exit(0);
p->data = e;
p->next = S->next;
S->next = p;
return OK;
}

Status Pop(LinkStack& S, ElemType& e)    //链式栈出栈
{
if (S->next == NULL) return ERROR;
e = S->next->data;
LNode* p = S->next;
S->next = p->next;
free(p);
return OK;
}

int main()
{
InitStack(S);
printf("顺序栈元素个数:%d\n", StackLength(S));
Push(S, 1);
Push(S, 2);
StackTraverse(S);
printf("顺序栈元素个数:%d\n", StackLength(S));
ElemType e;
GetTop(S, e);
printf("栈顶元素:%d\n", e);
Pop(S, e);
StackTraverse(S);
return 0;
}


• 0
点赞
• 0
评论
• 1
收藏
• 打赏
• 扫一扫，分享海报

11-27

04-18 5750
12-27 4504
11-01 2226
11-22 2848
12-12
10-29 2221
07-31 1437
08-07 281
07-18 2737
07-31 4816
10-04 31

¥2 ¥4 ¥6 ¥10 ¥20

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