数据结构第八篇——链栈
♥注:未经博主同意,不得转载。
链栈
链式存储的栈称为链栈。可用单链表来实现链栈,因此其节点结构与单链表的结构相同。下面给出这种结构的定义:
若要了解顺序栈的内容请跳转至http://www.cnblogs.com/tenjl-exv/p/7575549.html
链栈无栈满问题,空间可扩充,但有栈空问题,栈空的条件为top->next=NULL。插入与删除仅在栈顶处进行,链式栈的栈顶在链表头。
链栈的定义如下:
1 typedef int Data; 2 struct StackNode 3 { 4 Data data; 5 StackNode *next; 6 }; 7 8 class Stack 9 { 10 private: 11 StackNode *top; 12 public: 13 Stack() 14 { 15 top=new StackNode; 16 top->next=NULL; 17 } 18 ~Stack() 19 { 20 Clear(); 21 delete top; 22 } 23 24 void Push(Data e); 25 Data Pop(); 26 Data GetTop(); 27 bool IsEmpty(); 28 void Clear(); 29 void Print(); 30 };
相关操作算法如下:
1 //判断栈是否为空 2 bool Stack::IsEmpty() 3 { 4 if(top->next==NULL) 5 return true; 6 else 7 return false; 8 } 9 //取栈顶元素 10 Data Stack::GetTop() 11 { 12 if(top->next==NULL) 13 { 14 cout<<"栈空!"<<endl; 15 exit(0); 16 } 17 else 18 return top->next->data; 19 } 20 //进栈 21 void Stack::Push(Data x) 22 { 23 StackNode *p; 24 p=new StackNode; 25 p->data=x; 26 p->next=top->next; 27 top->next=p; 28 } 29 //出栈 30 Data Stack::Pop() 31 { 32 StackNode *p=NULL; 33 if(top->next==NULL) 34 { 35 cout<<"栈空"<<endl; 36 exit(0); 37 } 38 else 39 { 40 p=top->next; 41 Data retvalue=p->data; 42 top->next=p->next; 43 delete p; 44 return retvalue; 45 } 46 } 47 //清空栈 48 void Stack::Clear() 49 { 50 StackNode *p; 51 while(top->next) 52 { 53 p=top->next; 54 top->next=p->next; 55 delete p; 56 } 57 } 58 //打印数据 59 void Stack::Print() 60 { 61 StackNode *p; 62 p=top->next; 63 while(p) 64 { 65 cout<<p->data<<" "; 66 p=p->next; 67 } 68 cout<<endl; 69 }
测试部分则放在main函数:
1 int main() 2 { 3 Stack stack; 4 Data a[10]={1,5,8,7,9,5,6,7,4} ; 5 Data e; 6 if(stack.IsEmpty()) 7 cout<<"此栈为空"<<endl; 8 else 9 cout<<"此栈不空"<<endl; 10 11 for(int i=0;i<8;++i) 12 stack.Push(a[i]); 13 14 stack.Print(); 15 16 cout<<stack.GetTop()<<endl; 17 18 cout<<"进栈:"; 19 cin>>e; 20 stack.Push(e); 21 stack.Print(); 22 cout<<stack.GetTop()<<endl; 23 24 cout<<"出栈:"; 25 stack.Pop(); 26 stack.Print(); 27 cout<<stack.GetTop()<<endl; 28 29 if(stack.IsEmpty()) 30 cout<<"此栈为空"<<endl; 31 else 32 cout<<"此栈不空"<<endl; 33 34 cout<<"出栈:"; 35 stack.Pop(); 36 stack.Print(); 37 38 cout<<"清空栈:"<<endl; 39 stack.Clear(); 40 41 if(stack.IsEmpty()) 42 cout<<"此栈为空"<<endl; 43 else 44 cout<<"此栈不空"<<endl; 45 46 return 0; 47 }
简单的测试结果如下: