1. 程式人生 > >C++ 順序棧基本演算法實現

C++ 順序棧基本演算法實現

C++ 順序棧基本演算法

#ifndef SeqStack_h
#define SeqStack_h
#include <iostream>
using namespace std;
const int StackSize = 1024;
template <class T>
class SeqStack{
public:
    SeqStack(){top = -1;}
    SeqStack(T a[], int n);
    void Push(T  x);
    T Pop();
    T GetTop();
    bool Empty();
    
int GetLength(); void PrintSeqStack(); private: T data[StackSize]; int top; }; template<class T> SeqStack<T>::SeqStack(T a[], int n){ top = -1; if(n>StackSize) throw "上溢"; for(int i = 0;i< n;i++){ data[i] = a[i]; top++; } } template <class
T> bool SeqStack<T>::Empty(){ if(top <0) return true; else return false; } template <class T> void SeqStack<T>::Push(T x){ if(top >= StackSize-1) throw "上溢 "; top ++; data[top] = x; } template <class T> T SeqStack<T>::Pop(){ if(Empty()) throw
"下溢"; top--; return data[top+1]; } template <class T> T SeqStack<T>::GetTop(){ if(Empty()) throw "下溢"; return data[top]; } template <class T> int SeqStack<T>::GetLength(){ return top+1; } template <class T> void SeqStack<T>::PrintSeqStack(){ cout<<"入棧元素順序依次是:"<<endl; for(int i = 0;i<=top;i++){ cout<< data[i]<< " "; } cout << endl; } #endif /* SeqStack_h */