您的位置:首页 > 其它

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

2015-02-07 20:30 375 查看
头文件:函数的定义

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐