链栈

发布时间:2017-3-29 7:34:56 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"链栈",主要涉及到链栈方面的内容,对于链栈感兴趣的同学可以参考一下。

/************************************* * 2013.8.12 *************************************/ #include <iostream> #include <string> using namespace std; #define DEBUG_CONDITION 0 template <typename Elem_Type> struct node{ Elem_Type e; node<Elem_Type> *next; node(){next=NULL;} node(Elem_Type x):e(x),next(NULL){} ~node(){next=NULL;} }; template <typename Elem_Type> class Link_Stack{ public: Link_Stack():stack_size(0){top_pointer=NULL;} int size(){return stack_size;} void push(Elem_Type x){ if(stack_size){ node<Elem_Type> *temp = new_node(x); temp->next = top_pointer; top_pointer = temp; } else top_pointer = new_node(x); stack_size++; } void pop(){ if(stack_size){ node<Elem_Type> *temp = top_pointer->next; delete top_pointer; top_pointer = temp; stack_size--; } else if(DEBUG_CONDITION)cout << "empty_error" << endl; else return; } node<Elem_Type> *top(){return stack_size?top_pointer:NULL;} node<Elem_Type> down(){ if(stack_size){ Elem_Type temp = top()->e;pop(); return make_node(temp); } else { if(DEBUG_CONDITION)cout << "down_error" << endl; return node<Elem_Type>(); } } void clear(){ if(stack_size){ node<Elem_Type> *temp; for(int i=stack_size;i>0;--i){ temp = top_pointer->next; delete top_pointer; top_pointer = temp; } } stack_size = 0; top_pointer = NULL; } ~Link_Stack(){clear();} friend ostream & operator << (ostream &cout,const Link_Stack<Elem_Type> &LS){ cout << "LSstack size = " << LS.stack_size << endl; if(LS.stack_size){ node<Elem_Type> *temp = LS.top_pointer; for(int i=LS.stack_size;i>0;--i){ cout << "location " << i << " has "<< temp->e << endl; temp = temp->next; } } else cout << "This is empty." << endl; return cout; } private: int stack_size; node<Elem_Type> *top_pointer; node<Elem_Type> make_node(Elem_Type x){return node<Elem_Type>(x);} node<Elem_Type> *new_node(Elem_Type x){return new node<Elem_Type>(x);} }; int main(){ typedef int TYPE; TYPE d; string order; Link_Stack<TYPE> *LStack = new Link_Stack<TYPE>(); while(cin >> order){ if(order == "PUSH") {cin >> d;LStack->push(d);} else if(order == "POP") {LStack->pop();} else if(order == "DOWN") {if(LStack->size())cout << "location top is " << LStack->down().e << endl;else cout << "location top is empty." << endl;} else if(order == "CLEAR") {LStack->clear();} else if(order == "SHOW") {cout << *LStack << endl;} else if(order == "TOP") {if(LStack->top())cout << "location top is " << LStack->top()->e << endl;else cout << "location top is empty." << endl;} else break; } return 0; }

上一篇:MySQL Daemon failed to start
下一篇:ocx控件获取使用App的窗口句柄

相关文章

关键词: 链栈

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款