编写一个程序,实现链栈的各种基本运算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012651730/article/details/16118923

完成如下功能:

(1)初始化链栈s;

(2)判断链栈s是否非空;

(3)依次进链栈元素a,b,c,d,e;

(4)判断链栈s是否非空;

(5)输出链栈长度;

(6)输出从栈顶到栈底元素;

(7)输出出链栈序列;

(8)判断链栈s是否非空;

(9)释放链栈;



代码:

#include"iostream"
#include"malloc.h"
using namespace std;


typedef struct linknode
{
char data;
struct linknode * next;
}LiStack;


void InitStack(LiStack *& s)
{
s=(LiStack *)malloc(sizeof(LiStack));
s->next=NULL;
}


bool StackEmpty(LiStack *s)
{
return(s->next==NULL);
}


void Push(LiStack *& s,char e)
{
LiStack *p;
p=(LiStack *)malloc(sizeof(LiStack));
p->data=e;
p->next=s->next;
s->next=p;
}


int StackLength(LiStack *s)
{
LiStack * p=s;
int i=0;
while(p->next!=NULL)
{
i++;
p=p->next;
}
return(i);
}


void  Get(LiStack *s)
{
LiStack * p;
p=(LiStack *)malloc(sizeof(LiStack));
p=s->next;
while(p->next!=NULL)
{
cout << p->data << "  " ;
p=p->next;
}
cout << p->data << endl;
}


void  Pop(LiStack *s)
{
LiStack * p;
p=(LiStack *)malloc(sizeof(LiStack));
p=s->next;
while(p->next!=NULL)
{
cout << p->data << "  " ;
p=p->next;
}
cout << p->data << endl;
}


void DestoryStack(LiStack *&s)
{
LiStack * p=s,* q=s->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(p);
}


void main()
{
LiStack *s;
InitStack(s);
cout << StackEmpty(s) << endl;
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
cout << StackEmpty(s) << endl;
cout << StackLength(s) << endl;
Get(s);
Pop(s);
cout << StackEmpty(s) << endl;
DestoryStack(s);
}


展开阅读全文

没有更多推荐了,返回首页