堆栈之链表实现
2014-09-24 22:56
176 查看
#include<iostream> using namespace std; struct LinktackNode { LinktackNode* lastIn; int value; }; struct LinkStack { LinktackNode* top; LinktackNode* bottom; bool isEmpty; int cnt; }; LinkStack* createLinkStack() { LinkStack* st = (LinkStack*)malloc(sizeof(LinkStack)); LinktackNode* temp = (LinktackNode*)malloc(sizeof(LinktackNode)); temp->lastIn=NULL; st->top=temp; st->bottom=temp; st->cnt=0; st->isEmpty=true; return st; } bool isEmpty(LinkStack* st) { return st->isEmpty; } void push(LinkStack* st,int value) { LinktackNode* inNode = (LinktackNode*)malloc(sizeof(LinktackNode)); inNode->lastIn=st->top; inNode->value=value; st->top=inNode; st->isEmpty =((++st->cnt)==0); } bool pop(LinkStack* st,int* ans) { if(!st->isEmpty) { *ans=st->top->value; st->top=st->top->lastIn; st->isEmpty =((--st->cnt)==0); return 1; } return 0; } bool top(LinkStack* st,int* ans) { if(!st->isEmpty) { *ans=st->top->value; return 1; } return 0; } void clearStack(LinkStack* st) { int x; while(!st->isEmpty) { pop(st,&x); cout<<x<<" "; } cout<<endl; } void outPut(LinkStack* st) { LinktackNode* p = st->top; while(p!=st->bottom) { cout<<p->value<<" "; p=p->lastIn; } cout<<endl; } void main() { int len=10; LinkStack* st = createLinkStack(); int v; for(int i=0;i<len;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; outPut(st); clearStack(st); for(int i=0;i<len;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; outPut(st); pop(st,&v); cout<<v<<endl; outPut(st); top(st,&v); cout<<v<<endl; outPut(st); pop(st,&v); cout<<v<<endl; outPut(st); pop(st,&v); cout<<v<<endl; outPut(st); for(int i=0;i<5;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; outPut(st); if(!top(st,&v)) cout<<"fail"<<endl; else outPut(st); clearStack(st); if(!top(st,&v)) cout<<"fail"<<endl; else outPut(st); if(!top(st,&v)) cout<<"fail"<<endl; else outPut(st); cin>>len; }
相关文章推荐
- 在用链表实现堆栈时遇到的问题
- 堆栈与链表与队列代码实现
- 单向链表实现堆栈
- 考研数据结构与算法之堆栈的使用(四)链表实现的堆栈
- C 语言堆栈的实现,数组版本,链表版本(大师级的代码值得细细品味。)
- 基于数组或链表的堆栈实现
- ADT堆栈的链表实现
- 算法复习(5)链表实现的堆栈
- java实现堆栈、哈希表、链表
- Java中链表、堆栈、队列、二叉树、散列表等数据结构的实现
- 堆栈的两种实现形式:数组和链表
- java用链表实现堆栈和队列
- 用链表实现通用堆栈
- 堆栈的链表实现
- 4.3 堆栈的链表实现
- C++链表实现堆栈:LinkList:Build a linklist using C++ class Stack
- 用链表实现堆栈数据结构
- 分别用数组和链表实现堆栈(C语言版) - ahljjun的专栏 - 博客频道 - CSDN.NET
- 使用内部单向链表实现的一个简单堆栈
- 链表实现的堆栈程序(仅供自己学习使用)