利用链栈的基本运算,通过输入将字符进栈,然后输出其出栈序列

来源:互联网 发布:label mx 破解软件 编辑:程序博客网 时间:2024/04/18 10:48

头文件:函数的定义

#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <string.h>typedef char ElemType;typedef struct node{ElemType data;struct node *next;}LStackNode,*LinkStack;void InitStack(LinkStack *top);//将链栈初始化int StackEmpty(LinkStack top);//判断链栈是否为空int GetTop(LinkStack top,ElemType *e);//取栈顶元素int PushStack(LinkStack top,ElemType e);//进栈操作int PopStack(LinkStack top,ElemType *e);//出栈操作int StackLength(LinkStack top);//求表长操作void DestroyStack(LinkStack top);//销毁链表

函数的声明

#include "链式栈.h"void InitStack(LinkStack *top)//将链栈初始化{if((*top = (LinkStack)malloc(sizeof(LStackNode)))== NULL){exit(-1);}(*top)->next = NULL;}int StackEmpty(LinkStack top)//判断链栈是否为空{if(top->next == NULL){return 1;}else{return 0;}}int GetTop(LinkStack top,ElemType *e)//取栈顶元素{LStackNode *p;p = top->next ;if(!p){printf("栈已空!");return 0;}*e = p->data ;return 1;}int PushStack(LinkStack top,ElemType e)//进栈操作{LStackNode *p;if((p = (LinkStack)malloc(sizeof(LStackNode))) == NULL){printf("内存分配失败!");return 0;}p->data = e;p->next = top->next;top->next = p;return 1;}int PopStack(LinkStack top,ElemType *e)//出栈操作{LStackNode *p;p = top->next ;if(!p){printf("栈已空!");return 0;}top->next = p->next ;*e = p->data ;free(p);return 1;}int StackLength(LinkStack top)//求表长操作 {LStackNode *p;int count = 0;p = top;while(p->next != NULL){p = p->next ;count++;}return count;}void DestroyStack(LinkStack top)//销毁链表{LStackNode *p,*q;p = top;while(!p){q = p;p = p->next ;free(q);}}


函数的应用

#include "链式栈.h"//利用链栈的基本运算,通过输入将字符进栈,然后输出其出栈序列int main(void){LinkStack S;ElemType ch[50],e,*p;InitStack(&S);printf("请输入进栈的字符:\n");gets(ch);p = &ch[0];while(*p){PushStack(S,*p);p++;}printf("当前栈顶元素为:");if(GetTop(S,&e) == 0){printf("栈已空!");return 0;}else{printf("%4c\n",e);}printf("当前栈的元素个数是:%d\n",StackLength(S));printf("元素出栈的序列是:");while(!StackEmpty(S)){PopStack(S,&e);printf("%4c",e);}printf("\n");return 0;}


0 0
原创粉丝点击