栈--链表形式
实现下列操作。
1.初始化空栈。
2. 键盘输入字符,使得输入的字符依次入栈(结束符号自定,例如回车键(值为10)或'#')
每插入一个元素,必须输出当时的栈顶元素(调用GetLinkStackTop函数)。
3.判断链栈是否为空。输出判断结果。
4.调用出栈函数,打印出栈元素的值;反复此步骤,直至栈为空。
5.判断链栈是否为空。输出判断结果。
6.释放链栈。
1.初始化空栈。
2. 键盘输入字符,使得输入的字符依次入栈(结束符号自定,例如回车键(值为10)或'#')
每插入一个元素,必须输出当时的栈顶元素(调用GetLinkStackTop函数)。
3.判断链栈是否为空。输出判断结果。
4.调用出栈函数,打印出栈元素的值;反复此步骤,直至栈为空。
5.判断链栈是否为空。输出判断结果。
6.释放链栈。
#include <iostream>
#include <string.h>
using namespace std;
typedef char ElemType;
typedef struct linknode{
ElemType data;
struct linknode *next;
}LiStack;
void InitStack(LiStack * &s){ //initialize a LiStack
s = new LiStack;
s->next = NULL;
}
void Push(LiStack *&s,ElemType e){ //add the data to LiStack
LiStack *p;
p = new LiStack;
p->data=e;
p->next = s->next;
s->next=p;
}
bool Pop(LiStack * &s,ElemType &e){ //delete the data which is in the top
LiStack *p;
if(s->next==NULL)
return false;
p=s->next;
e=p->data;
s->next=p->next;
delete(p);
return true;
}
bool StackEmpty(LiStack * &s){ //judge the LiStack is empty or not
return (s->next==NULL);
}
bool GetTop(LiStack * &s,ElemType &e){ //get the data which is in the top
if(s->next==NULL)
return false;
e=s->next->data;
return false;
}
void DestroyStack(LiStack * &s){ //destroy the LiStack
LiStack *p =s ,*q=s->next;
while(q!=NULL){
delete(p);
p = q;
q = p->next;
}
delete(p);
}
int main(){
char c[100],ch;
ElemType e;
LiStack *s;
InitStack(s); //initialize the LiStack
int i=0;
while((ch=getchar())!='\n'){ //add the data to the LiStack and print the data in the top
if(ch!=' ')
c[i]=ch;
else continue;
Push(s,c[i]);
GetTop(s,e);
cout<<"after add the top data is:\t"<<e<<endl;
i++;
}
if(StackEmpty(s)) //judge the LiStack is empty or not
cout<<endl<<endl<<"the LiStack is empty"<<endl;
else cout<<endl<<endl<<"the LiStack is not empty"<<endl<<endl<<endl;
int j=1; //datele the top data and print it
while(s->next!=NULL){
Pop(s,e);
cout<<"the data "<<j<<" is:\t"<<e<<endl;;
j++;
}
if(StackEmpty(s)) //judge the LiStack is empty or not
cout<<endl<<endl<<"the LiStack is empty"<<endl<<endl<<endl;
else cout<<endl<<endl<<"the LiStack is not empty"<<endl<<endl<<endl;
DestroyStack(s); //destroy the LiStack
cout<<"the LiStack has been Destroy"<<endl;
return 0;
}