静态数组实现栈

vs2008运行正确

// SStack.cpp : 定义控制台应用程序的入口点。
//静态数组实现栈

#include "stdafx.h"
#include <iostream>
using namespace std;
const int Max = 50;

/*静态栈的条件
栈顶初始值:top=-1;
栈顶:总是指向刚刚压入的值
栈空:top=-1
栈满:top=Max-1
入栈: data[++top] = NewItem;
出栈:newItem = data[top--];
*/
template<class Type>
class SStack
{
public:
	SStack();
	SStack(const SStack<Type>& otherSStack);
	~SStack();
	SStack<Type> operator=(const SStack<Type>& otherSStack);
	void initSStack();
	bool isEmptySStack() const;
	bool IsFullSStack() const;
	void destorySStack();
	void pop(Type& popdata);
	void push(Type pushdata);

private:
	Type data[Max];
	int top;
};

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

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

template<class Type>
SStack<Type>::~SStack()
{
	//destorySStack();
}

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

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

template<class Type>
bool SStack<Type>::isEmptySStack() const
{
	if (top == -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

template<class Type>
bool SStack<Type>::IsFullSStack() const
{
	if (top == Max-1)
	{
		return true;
	}
	else
	{
		return false;
	}
	//return (top == Max-1);
}

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

template<class Type>
void SStack<Type>::pop(Type& popdata)
{
	if (isEmptySStack())
	{
		cout<<"栈空!"<<endl;
	}
	else
	{
		popdata = data[top--];
	}	
}

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


int _tmain(int argc, _TCHAR* argv[])
{
	SStack<int> s1;
	int a[4] = {3,4,5,6};
    for (int i=0; i<4; i++)
    {
		s1.push(a[i]);
    }	
	for (int i=0; i<4; i++)
	{
		int data;
		s1.pop(data);
		cout<<data<<" ";
	}
	cout<<endl;
	system("pause");
	return 0;
}




 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值