实验7 队列——卡片游戏
要求
- 创建队列类,使用数组描述的循环队列
- 实现卡片游戏
描述
假设桌上有一叠扑克牌,依次编号为 1-n(从上至下)。当至少还有两张的时候,可以进行操作:把第一张牌扔掉,然后把新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后。输入 n,输出最后剩下的牌。
格式
输入
一个整数 n,代表一开始卡片的总数。
输出
最后一张卡片的值。
思路与探讨
队列
整体思路描述
-
首先定义一个链队列,定义并实现构造函数、析构函数、头元素引用、尾元素引用、首元素
删除以及把元素 theElement 加入队尾的相关函数
-
然后把卡牌看做一整个队列
- 第一张牌扔掉即
首元素删除
- 新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后即
把当前首元素加入队尾
并将其删除
- 第一张牌扔掉即
若已看懂思路,试着自己写~
实现代码
#include<iostream>
using namespace std;
template <class T>//链表节点的结构定义
struct chainNode
{
//数据成员
T element;
chainNode<T> *next;
//方法
chainNode() {}
chainNode(const T& element)
{this->element = element;}
chainNode(const T& element, chainNode<T>* next)
{this->element = element;
this->next = next;}
};
template<class T>
class linkedQueue //链队列定义
{
public:
linkedQueue(int initialCapacity = 10)//初始化
{
queueFront = NULL; queueSize = 0;
}
~linkedQueue();//析构函数
T& front()//返回头元素的引用
{
if (queueSize == 0)
exit(1);
return queueFront->element;
}
T& back()//返回尾元素的引用
{
if (queueSize == 0)
exit(1);
return queueBack->element;
}
void pop();//删除首元素
void push(const T& theElement);//把元素theElement加入队尾
private:
chainNode<T>* queueFront;//头结点
chainNode<T>* queueBack;//尾结点
int queueSize;//队列元素的个数
};
template<class T>
linkedQueue<T>::~linkedQueue()
{
while (queueFront != NULL)
{//原理即往后一个,删掉上一个,直至删完
chainNode<T>* nextNode = queueFront->next;
delete queueFront;
queueFront = nextNode;
}
}
template<class T>
void linkedQueue<T>::pop()
{//删除首元素
if (queueFront == NULL)
exit(1);
chainNode<T>* nextNode = queueFront->next;
//删除第一个节点
delete queueFront;
queueFront = nextNode;
queueSize--;
}
template<class T>
void linkedQueue<T>::push(const T& theElement)
{//把元素theElement加入队尾
//为新元素申请节点
chainNode<T>* newNode = new chainNode<T>(theElement, NULL);
//在队列尾部添加新节点
if (queueSize == 0)
queueFront = newNode;
else
queueBack->next = newNode;
queueBack = newNode;
queueSize++;
}
int main()
{
int n;
linkedQueue<int> card;
cin >> n;
for(int i = 0;i < n;i++)
{
card.push(i + 1);//先把1~n排进去
}
for(int j = 0;j < n - 1;j++)
{
card.pop();//把第一张牌(即首元素)扔掉
card.push(card.front());//把新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后
card.pop();//把被移到最后的那张从上头删掉,完成统一
}
cout << card.front();
}