实验7 队列——卡片游戏

实验7 队列——卡片游戏

要求

  1. 创建队列类,使用数组描述的循环队列
  2. 实现卡片游戏

描述

假设桌上有一叠扑克牌,依次编号为 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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啦啦右一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值