栈是一种典型的线性表,它非常的简单,实现也很简单,但他的应用却非常的广泛,如函数的递归,一些撤销功能的实现等等!
栈是只能访问头节点的线性表!无论是插入,删除还是查找都只需要访问头节点。
他的实现一般有两种,一种是用向量表的实现,这种方法的有点在于节省空间,但缺点也比较明显,就是不够自由,容易出现栈溢出,当然我们可以通过另外申请空间来解决这个问题,但这样显得比较麻烦!还有一种方法是利用链表来实现!这种方法虽然造成了两倍的空间浪费,但基本不用担心栈溢出的情况,实现起来也非常简单!
下面就是我的c++代码实现:
//stack.h
#ifndef STASK_H #define STACK_H template<class objs_t> class stack{ struct node_t{ objs_t data; node_t *next; node_t ( objs_t &x=objs_t(), node_t *p=NULL ):data(x),next(p){} }; public: stack(){st=NULL;siz=0;} stack(const stack &p) { st=NULL;siz=0; node_t *n=p.st; clear(); while(n!=NULL) { push(n->data); n=n->next; } } ~stack(){ clear(); } void clear(){ while (!empty()) pop(); } bool empty()const{ return siz==0; } int size()const {return siz;} void push(objs_t &x) { if(siz!=0) st=new node_t(x,st); else st=new node_t(x,NULL); siz++; } objs_t top()const{ return st->data; } void pop(){ node_t *p=st; st=st->next; siz--; delete p; } private: node_t *st; int siz; }; #endif
原文:http://blog.csdn.net/alop_daoyan/article/details/22823357