/共享栈
(共享栈的内容)1, 建立空栈
2, 弹栈
3, 压栈
4, 判断栈空
5, 求栈
6, 打印栈
#include<iostream> #include<assert.h> using namespace std; template<typename T>class Stack; template<typename T>class Node {private: T data; Node<T> *next; public: Node(); friend class Stack<T>;
}; template<typename T>Node<T>::Node() { next=NULL; data=0; } template<typename T>class Stack {private: Node<T> *top; public: Stack(); ~Stack(); void MakeEmpty(); void Push( T & ); void Display(); bool IsEmpty(); T Pop(); T GetTop(); }; template<typename T>Stack<T>::Stack() { top=NULL; } template<typename T>Stack<T>::~Stack() { MakeEmpty(); } template<typename T>void Stack<T>::Push(T & x) { Node<T> *p; p=new Node<T>(); p->data=x; p->next=top; top=p; } template<typename T>T Stack<T>::Pop() { assert(!IsEmpty()); T x; Node<T> *temp; temp=top; top=top->next; x=temp->data; delete temp; return x; } template<typename T>void Stack<T>::Display() { Node<T> *p; p=top; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } template<typename T>bool Stack<T>::IsEmpty() { if(top==NULL) return true; else return false; } template<typename T>void Stack<T>::MakeEmpty() { Node<T> *temp; while(top!=NULL) { temp=top; top=top->next; delete temp; } } template<typename T>T Stack<T>::GetTop() { assert(!IsEmpty()); T x; x=top->data; return x; } void main() { Stack<int>s; int i; for(i=1;i<=10;i++) s.Push(i); s.Pop(); cout<<s.GetTop()<<endl; s.Display(); }
#include<iostream> #include<assert.h> using namespace std; template<typename T>class Stack {private: int top; T *elements; int maxSize; public: Stack(T ms); T GetTop(); int Pop(); void Push(T &); void Display(); bool IsFull(); bool IsEmpty(); }; template<typename T>Stack<T>::Stack(T ms) { top=-1; maxSize=ms; elements=new T[maxSize];
} template<typename T>bool Stack<T>::IsFull() { if(top==maxSize-1) return true; else return false; } template<typename T>bool Stack<T>::IsEmpty() { if(top==-1) return true; else return false; } template<typename T>void Stack<T>::Push(T & x) { assert(!IsFull()); elements[++top]=x; } template<typename T>int Stack<T>::Pop() { assert(!IsEmpty()); T x; x=elements[top--]; return x; } template<typename T>void Stack<T>::Display() { int i; for(i=top;i>=0;i--) cout<<elements[i]<<" "; cout<<endl; } template<typename T>T Stack<T>::GetTop() { if(top!=-1) return elements[top]; else return 0; } void main() { Stack<int>s(10); int i; for(i=1;i<=10;i++) s.Push(i); s.Display(); cout<<s.GetTop()<<endl; s.Pop(); s.Display(); }