静态数组实现栈

 VS2005运行通过,如有问题,请各位大牛指正。

/*静态栈的条件
栈顶初始值:top=-1;
栈顶:总是指向刚刚压入的值
栈空:top=-1
栈满:top=Max-1
入栈: data[++top] = NewItem;
出栈:newItem = data[top--];
*/

#include <iostream>
using namespace std;
const int Max = 50;
template<class Type>
class Stack
{
private:
	Type data[Max];
	int top;
public:
	Stack();
	Stack(const Stack<Type>& otherStack);
	~Stack();
	Stack<Type> operator=(const Stack<Type>& otherStack);
	void initStack();
	bool isEmptyStack() const;
	bool IsFullStack() const;;
	void destoryStack();
	void pop(Type& data);
	void push(Type data);
};

template<class Type>
Stack<Type>::Stack()
{
	top=-1;
}

template<class Type>
Stack<Type>::Stack(const Stack<Type>& otherStack)
{
	top = otherStack.top;
	if (!otherStack.isEmptyStack())
	{
		for (int i=0;i<=top;i++)
		{
			data[i] = otherStack.data[i];
		}
	}
}

template<class Type>
Stack<Type>::~Stack()
{

}

template<class Type>
Stack<Type> Stack<Type>::operator=(const Stack<Type>& otherStack)
{
	if (this != &otherStack)
	{
		if (!otherStack.isEmptyStack())
		{
			top = otherStack.top;
			for (int i=0;i<=top;i++)
			{
				data[i] = otherStack.data[i];
			}
		}
	}
	return *this;
}

template<class Type>
void Stack<Type>::initStack()
{
	top=-1;
}

template<class Type>
bool Stack<Type>::isEmptyStack() const
{
	return (top==-1);
}

template<class Type>
bool Stack<Type>::IsFullStack() const
{
	return (top==Max-1);//top表示指针位置,最大为Max-1
}

template<class Type>
void Stack<Type>::destoryStack()
{
	top=-1;
}

template<class Type>
void Stack<Type>::pop(Type& NewItem)
{
	if (isEmptyStack())
	{
		cout<<"栈空"<<endl;
	}
	else
	{
		NewItem = data[top--];
	}
}

template<class Type>
void Stack<Type>::push(Type NewItem)
{
	if (IsFullStack())
	{
		cout<<"栈满!"<<endl;
	}
	else
	{
		data[++top]= NewItem;
	}
}

int main()
{
	Stack<int> s;
	Stack<int> s1;
	s1=s;
	int a[4]={1,2,3,4};
	for (int i=0;i<4;i++)
	{
		s1.push(a[i]);
	}
	for (int i=0;i<4;i++)
	{
		int temp;
		s1.pop(temp);
		cout<<temp<<endl;
	}
	system("pause");
	return 0;
}

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值