蓝桥杯—盾神与条状项链(C++实现)

思路:

  直接使用STL的list容器。

  分两种情况:

  1.DEL Q。通过迭代器,找到Q的位置(看不懂迭代器的可以参考这篇文http://www.cnblogs.com/yc_sunniwell/archive/2010/06/25/1764934.html),然后直接调用void remove( const TYPE &val )函数即可。

  2.ADD P Q。首先找出P所在的位置,通过迭代器实现,之后将Q插入到P之前,调用iterator insert( iterator pos, const TYPE &val )函数即可实现。

代码如下:

 1 #include<list>
 2 #include<string>
 3 #include <iostream>
 4 using namespace std;
 5 void operate(int num,int step){
 6     string str;int P,Q;//str为"DEL"或"ADD",P为颜色为P的珠子,Q是颜色为Q的珠子 
 7     list<int> *ls=new list<int>;
 8     for(int i=0;i<num;i++){    //输入链表值 
 9         cin>>Q;
10         ls->push_back(Q);
11     }
12     for(int i=0;i<step;i++){
13         cin>>str;
14         if(str=="DEL"){//DEL P:表示把颜色为P的珠子去掉,如果它不在端点处,则需要把它旁边的两颗珠子连起来。例如某时刻项链状态为1 4 5 8,则执行DEL 4会变成1 5 8,执行DEL 1会变成4 5 8。
15             cin>>Q; 
16             ls->remove(Q);
17         }else{//ADD P Q:表示在颜色为P的珠子前面加上一个颜色为Q的珠子。
18             cin>>P>>Q;
19             list<int>::iterator it=ls->begin();
20             while(*it!=P){
21                 it++;
22             }
23             ls->insert(it,Q);
24         }
25         
26     }    
27     list<int>::iterator it=ls->begin();
28     cout<<ls->size()<<endl;
29     while(it!=ls->end()){
30         cout<<*it<<" ";
31         it++;
32     }
33     delete ls;
34 } 
35 
36 int main(){//测试代码 
37     int num,step;
38     cin>>num>>step;
39     operate(num,step);
40     return 0;
41 }

 

转载于:https://www.cnblogs.com/ytz1996/p/6287718.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值