栈实现代码一

1.复习两个知识点先:

  1. define语句是不要分号结尾的(这个很容易记住,因为我们写#include语句的时候也没有加过分号的把!);

  2. 模板类的声明方法:注意我们在类体外定义类的函数的时候,一定要为每个函数加上template语句,并且使用域作用符::时要指定类型;

2.实现说明:

这里是用数组实现的栈,下一次使用链表实现之。

在使用数组实现栈的过程中,有个问题值得讨论,就是这个栈顶指针(top)到底应该指向栈顶的那个元素还是指向栈顶那个元素的下一个空位置呢?

这两种方法都是可行的。本代码使用的前一种,其带来了如下好处:

  1. 遍历输出栈时,计数器i0变化到top就可以了,即for(int i = 0; i < top; i++)就可以了,这和处理边界问题时遵循的“前闭后开”是吻合的;

  2. 判定栈为空时,直接判定其是不是0即可,这和我们的语言习惯是吻合的;

我目前发现的这么做的最好的有点就是以上两点了。

3.代码:

#include <iostream>
using namespace std;
#define EMPTY 0 
template <class type>
class stack{
public:
	stack(const int stackSize);
	stack(const stack<type> &otherStack);
	~stack();

	void destroyStack();
	void copy(const stack<type> &otherStack);
	bool isEmpty();
	bool isFull();
	void push(const type x);
	type top();
	type pop();

	void print();

public:
	int maxSize;
	int stackTop;
	int *array;
};
template <class type>
stack<type>::stack(const int stackSize)
{
	if(0 > stackSize)maxSize = 100;
	else maxSize = stackSize;
	stackTop = 0;
	array = new type[maxSize];
	for(int i = 0; i< maxSize; i++)
		array[i] = 0;
}

template <class type>
stack<type>::stack(const stack<type> &otherStack)
{
	if(NULL == otherStack)return;
	copy(otherStack);
}

template <class type>
void stack<type>::copy(const stack<type> &otherStack)
{
	maxSize = otherStack.maxSize;
	array = new type[maxSize];
	stackTop = otherStack.stackTop;
	for (int i = 0; i < stackTop; i++)
		array[i] = otherStack.array[i];
}

template <class type>
void stack<type>::print()
{
	for(int i = 0; i < stackTop; i++)
		cout << array[i] << endl;
	cout << "print stack over" << endl;
}
template <class type>
bool stack<type>::isEmpty()
{
	if(EMPTY == stackTop) return true;
	else return false;
}
template <class type>
bool stack<type>::isFull()
{
	if(stackTop == maxSize)return true;
	else return false;
}
template <class type>
void stack<type>::push(const type x)
{
	if( true == isFull() )return;
	array[stackTop++] = x;
}
template <class type>
type stack<type>::top()
{
	if(true == isEmpty() )return -1;
	return array[stackTop-1];
}
template <class type>
type stack<type>::pop()
{
	if(true == isEmpty() )return -1;
	return array[--stackTop];
}
template <class type>
stack<type>::~stack()
{
	delete [] array;
}
int main()
{
	stack<int> s(10);
	for(int i = 0; i<11; i++)
		s.push(i);
	s.print();
	s.pop();
	s.print();
	return 0;
}

4.总结:

写栈的代码时,要注意进栈和出栈时要判定栈是否空或者是否满,这是必须要考虑到的,否则必然出错。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值