链表实现栈
【摘要】 栈,是操作受限的线性表,只能在一端进行插入删除。
其实就是带尾指针的链表,尾插
#include <stdio.h>#include <stdlib.h>#define OK 1#define ERROR 0#define Status int#define SElemType int//只在头部进行插入和删除(不带头结点)typedef stru...
栈,是操作受限的线性表,只能在一端进行插入删除。
其实就是带尾指针的链表,尾插
-
#include <stdio.h>
-
#include <stdlib.h>
-
#define OK 1
-
#define ERROR 0
-
#define Status int
-
#define SElemType int
-
//只在头部进行插入和删除(不带头结点)
-
typedef struct LNode
-
{
-
SElemType data;
-
struct LNode *next;
-
}LNode, *LinkList;
-
-
typedef struct
-
{
-
LNode *top;
-
LNode *base;
-
int length;
-
}LinkStack;
-
-
-
Status InitStack(LinkStack &S)
-
{
-
S.base = NULL;
-
S.top = NULL;
-
S.length = 0;
-
return OK;
-
}
-
-
Status GetTop(LinkStack S, SElemType &e)
-
{
-
if(S.length == 0)
-
return ERROR;
-
e = S.top->data ;
-
return OK;
-
}
-
-
Status Push(LinkStack &S, SElemType e)
-
{
-
LNode *newNode = (LNode *)malloc(sizeof(LNode));
-
newNode->data = e;
-
newNode->next = S.top;
-
S.top = newNode;
-
if(!S.base)
-
S.base = newNode;
-
++S.length;
-
return OK;
-
}
-
-
Status Pop(LinkStack &S, SElemType &e)
-
{
-
LNode *p = S.top;
-
if(S.length == 0)
-
return ERROR;
-
e = S.top->data;
-
S.top = S.top->next;
-
free(p);
-
--S.length;
-
return OK;
-
}
-
-
void PrintStack(LinkStack S)
-
{
-
LNode *p = S.top;
-
printf("由栈顶到栈底:");
-
while (p)
-
{
-
printf("%d ",p->data);
-
p = p->next;
-
}
-
printf("\n");
-
}
-
-
-
int main(void)
-
{
-
LinkStack LS;
-
InitStack(LS);
-
Push(LS,11);
-
Push(LS,22);
-
Push(LS,33);
-
Push(LS,44);
-
Push(LS,55);
-
PrintStack(LS);
-
SElemType e ;
-
GetTop(LS , e);
-
printf("栈顶元素是: %d\n",e);
-
Pop(LS,e);
-
PrintStack(LS);
-
Pop(LS,e);
-
PrintStack(LS);
-
-
-
-
return 0;
-
}
文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。
原文链接:fantianzuo.blog.csdn.net/article/details/83025150
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)