編寫一個程式,實現鏈棧的各種基本運算
阿新 • • 發佈:2019-02-20
完成如下功能:
(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); }