生活随笔
收集整理的這篇文章主要介紹了
SeqStack(Templateclass T)实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
順序表實現(xiàn)模板棧(第二次)
這是發(fā)過的一個版本的棧的鏈接
這次用模板再做了一遍
配有測試過的main函數(shù),可以直接學(xué)習(xí)使用。
#include <iostream>
using namespace std;
template<
class T>
class SeqStack{
public:SeqStack(
int sz =
50);~SeqStack(){
delete[]element; };
bool push(
const T& x);
bool pop();
bool getTop(T& x)
const;
bool isEmpty()
const;
bool isFull()
const;
int getSize()
const;
void makeEmpty();
template<
class U>
friend ostream&
operator<<(ostream& os, SeqStack<U> s);
private:T* element;
int maxsize, top;
};
template<
class T>
SeqStack<T>::SeqStack(
int sz) {
if (sz <=
0){element = NULL;}
else {element =
new T[sz];}maxsize = sz;top = -
1;
}
template<
class T>
bool SeqStack<T>::push(
const T& x){
if (isFull()){
return false;}
else {element[++top] = x;
return true;}
}
template<
class T>
int SeqStack<T>::getSize()
const {
return top +
1;
}
template<
class T>
bool SeqStack<T>::pop(){
if (isEmpty()){
return false;}
else{top--;
return true;}
}
template<
class T>
bool SeqStack<T>::getTop(T& x)
const{
if (isEmpty()){
return false;}
else {x = element[top];
return true;}
}
template<
class T>
void SeqStack<T>::makeEmpty(){top = -
1;
}
template<
class T>
bool SeqStack<T>::isFull()
const{
return top >= maxsize -
1;
}
template<
class T>
bool SeqStack<T>::isEmpty()
const{
return top == -
1;
}
template<
class U>
ostream&
operator<<(ostream &os, SeqStack<U> s){os<<
"maxsize = "<< s.maxsize<<
" top = "<< s.top<< endl;
for (
int i = s.top; i >=
0; --i){os << s.element[i];
if (i !=
0)os <<
" -> "; }
return os;
}
int main(){SeqStack<
int> s;
for (
int i =
0; i <
20; ++i)s.push(i*
12 -
1);
cout << s<< endl;
for (
int i =
0; i <
10; ++i)s.pop();
cout << s<< endl;
}
總結(jié)
以上是生活随笔為你收集整理的SeqStack(Templateclass T)实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。