题目如下:
改写顺序栈的进栈成员函数Push(x),要求当栈满时执行一个stackFull()操作进行栈满处理。其功能是:动态创建一个比原来大两倍的数组,代替原来的栈数组,原来的栈数组中的元素占据新数组的前maxSize位置。
下面为博主自己写的代码:
#ifndef STACK_H_
#define STACK_H_
template<class T>
class SeqStack{
private:
T * item;
int top;
int maxSize;
void stackFull();
public:
SeqStack(int sz = 10);
~SeqStack();
bool Push(const T & x);
int size(){ return maxSize; }
};
template<class T>
SeqStack<T>::SeqStack(int sz)
{
maxSize = sz;
top = -1;
item = new T[maxSize];
}
template<class T>
SeqStack<T>::~SeqStack()
{
delete[] item;
}
template < class T >
void SeqStack<T>::stackFull()
{
T * newArray = new T[3 * maxSize];
for (int i = 0; i <= top; i++)
{
newArray[i] = item[i];
}
maxSize = maxSize * 3;
delete[] item;
item = newArray;
}
template<class T>
bool SeqStack<T>::Push(const T & x)
{
if (top == maxSize - 1)
{
stackFull();
top++;
item[top] = x;
return true;
}
else
{
top++;
item[top] = x;
return true;
}
}
#endif
// ex3-9.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stack.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
SeqStack<int> s1(5);
for (int i = 0; i < 5; i++)
{
int value;
cout << "Please enter the value: ";
cin >> value;
s1.Push(value);
}
cout << endl;
int size = s1.size();
cout << "The size of the stack: " << size << endl;
for (int i = 0; i < 2; i++)
{
int value;
cout << "Please enter the value: ";
cin >> value;
s1.Push(value);
}
int size2 = s1.size();
cout << "After while the size of the stack: " << size2 << endl;
system("pause");
return 0;
}