其使用可变数组实现方式: 实现平台:widows 7 vs2010
ResizingArrayStack.h
#pragma once
template<class T>
class ResizingArrayStack
{
private:
T *data;//数据
int capacity;//栈的大小
int top;//栈顶的位置
void resize(int capacity);
public:
ResizingArrayStack(void);
~ResizingArrayStack(void);
void push(T item);
T pop();
bool isEmpty();
};
template<class T>
ResizingArrayStack<T>::ResizingArrayStack(void)
{
data = new T[1];
this->capacity = 1;
this->top = 0;
}
template<class T>
ResizingArrayStack<T>::~ResizingArrayStack(void)
{
delete data;
}
template<class T>
void ResizingArrayStack<T>::push(T item)
{
if(this->capacity == this->top)
{
this->resize(this->capacity*2);
}
this->data[this->top++] = item;
}
template<class T>
void ResizingArrayStack<T>::resize(int capicity)
{
T* new_data = new T[capicity];
this->capacity = capicity;
for(int i = 0;i<this->top;i++)
{
new_data[i] = data[i];
}
delete []data;
data = new_data;
}
template<class T>
bool ResizingArrayStack<T>::isEmpty()
{
return this->top == 0;
}
template<class T>
T ResizingArrayStack<T>::pop()
{
if(this->isEmpty())
{
throw "stack is empty";
}
if(this->capacity/4 == this->top)
{
this->resize(this->capacity/2);
}
return data[--this->top];
}
说明:这里我在重新分配栈空间大小时候不是采用栈满的时候增加一个空间。这样的话我们需要做多次copy工作。
首次入栈N个元素所需要copy次数:1 + 2 + … + N ~ N^2/2(二分之N的平方)
我们这里采用如果栈满的情况分配一个当前栈内容2倍大小的空间。
首次入栈N个元素所需要copy次数:N + (2 + 4 + 8 + … + N) ~ 3N.
测试主函数;
#include "stdafx.h"
#include"ResizingArrayStack.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ResizingArrayStack<int> stack_test;
try
{
for(int i = 0;i < 10;i++)
stack_test.push(i);
for(int i = 0;i < 9;i++)
cout<<stack_test.pop()<<endl;
}
catch(const char *ex)
{
cout<<ex<<endl;
}
system("pause");
return 0;
}
测试结果: