杨辉三角(c++队列模板实现)

在这里插入图片描述

#include<iostream>
using namespace std;

template <class T>
class LinkQueue{
	struct LinkQueueNode
	{
		T data;
		LinkQueueNode *link;
		LinkQueueNode(T & theData, LinkQueueNode * n=NULL):data(theData),link(n){}
	};
	LinkQueueNode* front;
	LinkQueueNode* back;
	
public:
	LinkQueue(); //构造函数 
	~LinkQueue(); //析构函数 
	void EnQueue(T& element); //入队列 
	T DelQueue(); //出队列 
	T& GetFront(); //返回队列的头 
	void MakeEmpty(); //清空队列 
	bool IsEmpty();  //判断队列是否为空 
}; 

template <class T>
LinkQueue<T>::LinkQueue()
{
	front = back = NULL;
}

template <class T>
LinkQueue<T>::~LinkQueue()
{
	this->MakeEmpty();
}

template <class T>
void LinkQueue<T>::EnQueue(T& value)
{
	if(this->IsEmpty())
		front = back = new LinkQueueNode(value);
	else
		back = back->link = new LinkQueueNode(value);
}

template <class T>
T LinkQueue<T>::DelQueue()
{
	LinkQueueNode* old = front;
	T data = old->data;
	front = front->link;
	delete old;
	return data;
}

template <class T>
T& LinkQueue<T>::GetFront()
{
	if(!IsEmpty())
		return front->data;
}

template <class T>
void LinkQueue<T>::MakeEmpty()
{
	while(!this->IsEmpty())
	{
		this->DelQueue();
	}
}

template <class T>
bool LinkQueue<T>::IsEmpty()
{
	return front == NULL;
}

//赋值 
template <class T>
void evaluate(LinkQueue<T>& ori,LinkQueue<T>& target){
	ori.MakeEmpty();
	while(!target.IsEmpty()){
		int tmp_value = target.DelQueue();
		ori.EnQueue(tmp_value);
	}
}

int main()
{
	cout<<"————欢迎使用杨辉三角行计算器!————"<<endl;
	cout<<"————————author---jql——————————"<<endl; 
	cout<<"请输入杨辉三角阶数i(i>2):";
	int num;
	cin>>num;
	LinkQueue<int> ori; //先创建一个队列并初始化队列元素为1 
	
	int ini_value = 1;
	ori.EnQueue(ini_value);
	ori.EnQueue(ini_value);
	LinkQueue<int> next;
	for(int i=0;i<num-2;i++){
		next.EnQueue(ini_value);
		while(!ori.IsEmpty())
		{
			int i=ori.DelQueue();
			if(!ori.IsEmpty())
			{
				int tmp = i+ori.GetFront();
				next.EnQueue(tmp);
			}
			if(ori.IsEmpty())
				next.EnQueue(i);
		}
		evaluate(ori,next);
	}
	cout<<"杨辉三角第"<<num<<"行内容如下:"<<endl;
	while(!ori.IsEmpty()){
		cout<<ori.DelQueue()<<" ";
	} 
	cout<<endl;

	system("PAUSE");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41462017/article/details/84201482