数据结构实验7

队列

要求
创建队列类,采用链式描述
实现卡片游戏
描述
假设桌上有一叠扑克牌,依次编号为1-n(从上至下)。当至少还有两张的时候,可以进行操作:把第一张牌扔掉,然后把新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后。输入n,输出最后剩下的牌。
格式
输入
一个整数n,代表一开始卡片的总数。
输出
最后一张卡片的值。
样例
输入
100

输出
72

限制
1s, 64MB for each test case.

#include<iostream>
#include<cstdlib>
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();
      bool empty() const 
           {return queueSize == 0;}
      int size() const
          {return queueSize;}
      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&);
   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)
{
   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> lq;
	cin>>n;
	for(int i=0;i<n;i++)
		lq.push(i+1);
	for(int j=1;j<n;j++)
	{
		lq.pop();
		lq.push(lq.front());
		lq.pop();
	}
	cout<<lq.front();
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值