栈有 2种实现:一种使用队列,另一种使用链表。
当栈中有n个项时,这一实现用s[0],s[1],,..s[N-1]来保存他们。下面的代码并未实现对诸如向一个满栈中压入元素(或者从一个空栈中弹出元素)这类操作的错误检测。
template<class T> class Stack { private: T *s; int n; public: Stack(int maxN) { s=new T[maxN]; n=0; } int empty() const { return n==0;} void push(T t) { s[n++]=t; } T pop() { return s[--n]; } };
用链表实现:
#include<iostream> using namespace std; template<class T> class Stack { private: struct node { T t; node *next; node(T x,node *t):t(x),next(t){ } }; typedef node *Link; Link head; public: Stack( ) { head=0; } int empty() const { return head==0;} void push(T x) { head=new node(x,head); } T pop() { Link t=head->next; T v=head->t; delete head; head=t; return v; } }; int main() { Stack<int> s; for(int i=0;i<10;i++) s.push(i); for(int i=0;i<10;i++) cout<<s.pop()<<ends; }
注意,链表构造时是从右向左。