오늘 Awei 스택을 시작하는 것은 그것을 배울 수 있습니다! !
(먼저, 약간의 지식을 보완 하는 기능 매개 변수로 인용 )
첫째 추상 클래스를 스택 :
template<class T>
class stack
{
public:
virtual ~stack(){}//析构函数
virtual bool empty()const=0;//返回true,当且仅当栈为空
virtual int size()const=0;//返回栈中元素个数
virtual T& top()=0;//返回栈顶元素的引用
virtual void pop()=0;//删除栈顶元素
virtual void push(const T& theElement)=0;//将元素theElement压入栈顶
};
설명 스택 어레이 클래스의 ArrayList와 스택에서 파생 된 클래스 derivedArrayStack (유도 : 유도)
//操作在数组尾进行,即栈顶在数组尾
template<class T>
class derivedArrayStack:private arrayList<T>,public:stack<T>
{
public:
//动态创建一维数组,数组长度是initialCapacity
derivedArrayStack(int initialCapacity=10):arrayLength<T>(initialCapacity){}//构造函数
bool empty()const
{
return arrayList<T>::empty();
}
int size()const
{
return arrayList<T>::size();
}
T& top()
{
if(arrayList<T>::empty())
throw stackEmpty();
return get(arrayList<T>::size()-1);
}
void pop()
{
if(arrayList<T>::empty())
throw stackEmpty();
erase(arrayList<T>::size()-1);
}
void push(const T& theElement)
{
insert(arrayList<T>::size(),theElement);
}
};
스택 어레이의 더 나은 성능을 달성하는 방법을 획득하기 위해, 방법은 클래스의 발전 요소를 스택하는 스택 모두를 포함하는 배열을 사용하여이.
범주 인 ArrayStack :
template<class T>
class arrayStack:public stack<T>
{
public:
arrayStack(int initialCapacity=10);
~arrayStack(){delete [] stack;}
bool empty()const
{
return stackTop==-1;
}
int size()const
{
return stackTop+1;
}
T& top()
{
if(stackTop==-1)
throw stackEmpty();
return stack[stackTop];
}
void pop()
{
if(stackTop==-1)
throw stackEmpty;
stack[stackTop--].~T();//T的析构函数
}
void push(const T& theElement);
private:
int stackTop;//当前栈顶元素的索引
int arrayLength;//栈容量
T *stack;//元素数组
};
생성자 (O 시간 복잡도 (1))
template<class T>
arrayStack<T>::arrayStack(int initialCapacity)
{
if(initialCapacity<1)
{
ostringstream s;
s<<"Initial capacity ="<<initialCapacity<<"Must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength=initialCapacity;
stack=new T[arrayLength];
stackTop=-1;
}
실현 푸시 기능
template<class T>
void arrayStack<T>::push(const T& theElement)
{
if(stackTop==arrayLength-1)//如果空间已满,容量加倍
{
changeLength1D(stack,arrayLength,2*arrayLength);
arrayLength*=2;
}
//在栈顶插入
stack[++stackTop]=theElement;
}