06.栈.链栈

来源:互联网 发布:一键转发朋友圈 源码 编辑:程序博客网 时间:2024/05/23 16:00

链栈

#include <stdio.h>#include <stdlib.h>#define MAXSIZE 15//符号常量,代表线性表存储空间初始分配量#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int SElemType;//SElemType这里假设为int,可以根据需要进行更改typedef int Status;//Status是函数的类型,其值是函数结果状态代码,如OK等/*链栈结点*/typedef struct stackNode{SElemType data;struct stackNode *next;}StackNode;/*链栈结构*/typedef struct linkStack{StackNode *top;int count;}LinkStack;/*构造一个空栈S*/Status InitStack(LinkStack *S){S->top=NULL;S->count=0;return OK;}/*插入元素e为新的栈顶元素*/Status Push(LinkStack *S,SElemType e){StackNode *s=(StackNode *)malloc(sizeof(StackNode));s->data=e;s->next=S->top;S->top=s;S->count++;return OK;}/*遍历显示链栈*/Status StackTraverse(LinkStack S){StackNode *p=S.top;while(p){printf("%d ",p->data);p=p->next;}printf("\n");return OK;}/*若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR*/Status Pop(LinkStack *S,SElemType *e){ StackNode *p;if(S->top==NULL)return ERROR;*e=S->top->data;p=S->top;//p指向栈顶结点S->top=S->top->next;//使得栈顶指针下移一位,指向后一结点free(p);//释放结点preturn OK;}/*若栈S为空栈,则返回TRUE,否则返回FALSE*/Status StackEmpty(LinkStack S){ if(S.count==0)return TRUE;elsereturn FALSE;}/*若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR*/Status GetTop(LinkStack S,SElemType *e){if(S.top==NULL)return ERROR;*e=S.top->data;return OK;}/* 返回S的元素个数,即栈的长度 */int StackLength(LinkStack S){ return S.count;}/*把S置为空栈*/Status ClearStack(LinkStack *S){StackNode *p,*q;p=S->top;while(p){q=p;p=p->next;free(q);}S->top=NULL;S->count=0;return OK;}int main(){LinkStack s;int j;SElemType e;if(InitStack(&s)==OK){for(j=1;j<=10;j++)Push(&s,j);}printf("栈中元素依次为:");    StackTraverse(s);Pop(&s,&e);printf("弹出的栈顶元素e = %d\n",e);printf("栈中元素依次为:");    StackTraverse(s);printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));GetTop(s,&e);    printf("栈顶元素e = %d,栈的长度为%d\n",e,StackLength(s));ClearStack(&s);    printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));return 0;}


0 0
原创粉丝点击