1 #include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4 5 typedef struct LNode 6 { 7 int data; 8 struct LNode *next; 9 }LNode;//栈结点定义 10 11 void InitStack(LNode *&S) 12 { 13 S=(LNode*)malloc(sizeof(LNode)); 14 S->next=NULL; 15 } 16 17 int IsEmpty(LNode *S) 18 { 19 if(S->next==NULL) 20 return 1; 21 else 22 return 0; 23 } 24 25 void Push(LNode *&S,int e) 26 { 27 LNode *p; 28 p=(LNode*)malloc(sizeof(LNode)); 29 p->next=NULL; 30 p->data=e; 31 32 p->next=S->next; 33 S->next=p; 34 } 35 36 int Pop(LNode *&S,int &e) 37 { 38 LNode *p; 39 if(S->next==NULL) 40 return 0; 41 42 p=S->next; 43 e=p->data; 44 S->next=p->next; 45 free(p); 46 return 1; 47 } 48 49 void Print(LNode *S) 50 { 51 if(S->next==NULL) 52 { 53 cout<<"链栈为空! "<<endl; 54 return; 55 } 56 LNode *p; 57 p=S->next; 58 cout<<"\n链栈中的元素为(栈顶->栈底):\n"; 59 while(p!=NULL) 60 { 61 cout<<" "<<p->data<<" "; 62 p=p->next; 63 } 64 return; 65 } 66 67 int main() 68 { 69 int i,e; 70 LNode *S; 71 InitStack(S); 72 for(i=0;i<10;++i) 73 Push(S,i); 74 Print(S); 75 76 77 cout<<"\n\n依次出栈的四个元素为:\n"; 78 for(i=0;i<4;++i) 79 { 80 Pop(S,e); 81 cout<<" "<<e<<" "; 82 } 83 //cout<<"\n\n"; 84 Print(S); 85 if(IsEmpty(S)==1) 86 cout<<"\n此时,链栈为空!\n"; 87 else 88 cout<<"\n此时,链栈非空!\n"; 89 90 return 0; 91 }