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 */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM