標籤:
堆棧(簡稱棧) 是一種操作受限的線性表,只允許在表的同一端進行插入和刪除操作,且這些操作是按先進後出的原則進行的。
template <class T>struct SLNode{T data; //資料域SLNode<T> *next; //指標域SLNode(SLNode *nextNode = NULL) //建構函式{next = nextNode;}SLNode(const T &item, SLNode *nextNode = NULL) //建構函式{data = item;next = nextNode;}};//順序棧template <class T>class AStack{public:AStack(int MaxStackSize) //建構函式{size = MaxStackSize;stackArray = new T[MaxStackSize];top = -1;}~AStack() //解構函式{delete []stackArray;}bool Push(const T &item) //向棧頂壓入一個元素{if (IsFull()){cout << "Pushing into a full stack!" << endl;return false;}stackArray[++top] = item;return true;}bool Pop(T &item) //從棧頂彈出一個元素{if (IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = stackArray[top--];return true;}bool Peek(T &item) const //存取棧頂元素{if (IsEmpty()){cout << "Peeking from an empty stack!" << endl;return false;}item = stackArray[top];return true;}int IsEmpty() const //檢測棧是否為空白{return top == -1;}int IsFull() const //檢測是否滿棧{return top == size-1;}void clear() //清空棧{top = -1;}private:int size; //數組的規模T *stackArray; //存放堆棧元素的數組int top; //棧頂所在數組元素的下標};//鏈式棧類LStack的定義和實現template <class T>class LStack{public:LStack() //建構函式{top = NULL;}~LStack() //解構函式{clear();}void clear() //清空棧{SLNode<T> *temp;while(!IsEmpty()){temp = top->next;delete top;top = temp;}}bool Push(const T &item) //向棧頂壓入一個元素{top = new SLNode<T>(item, top);return true;}bool Pop(T &item) //從棧頂彈出一個元素{if(IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = top->data;SLNode<T> *temp = top;top = top->next;}bool Peek(T &item) const //讀取棧頂元素{if(IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = top->data;return true;}int IsEmpty() const{return top == NULL;}private:SLNode<T> *top;};
資料結構-棧的一些基礎操作c++代碼