数据结构课后题目源码

题目如下:

改写顺序栈的进栈成员函数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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值