链表类问题(循环链表,双向链表)
输入1个数字和多个字符,中间均以空格隔开。假设数字取值为m(范围1~9),后面字符个数为n。假设n个字符围成一圈,从第一个字母开始循环报数,当数 到m以后,第m个字母就出列,直到这n个字母全部出列。最后,按照出列的顺序输出这些字母,中间仍以空格隔开。取值范围:m为1到9, 字符个数n大于1 小于20。
| 输入: |
第一个为数字,后面为多个字符,均以空格隔开 |
| 输出: |
输出重新排列后的字符,以空格隔开 |
| 样例输入: |
3 a b c d e f g h i |
| 样例输出: |
c f i d h e b g a |
| 答案提示: |
建议采用循环链表 |
单向链表也可以做这个题目。
1 view plaincopy to clipboardprint?
2 #include "iostream" 3 #include <iomanip>
4 #include <string.h>
5 #include <string>
6 #include <vector>
7 #include <cmath>
8 #include <cctype>
9 #include <algorithm>
10 #include <set>
11usingnamespace std;
1213 typedef struct node
14{
15char ch;
16 node * pre;
17 node * next;
18}node;
19int n;
20int k;
21 node *first;
22void read()
23{
24 k=0;
25 cin >>n;
26char c;
27 first = NULL;
28 node * p = first;
29 node * q = NULL;
30while(cin >>c)
31 {
32 ++k;
33if(k == 1)
34 {
35 p = new node();
36 p->pre = NULL;
37 p->next = NULL;
38 p->ch = c;
39 first = p;
40 }
41else42 {
43 q = new node();
44 q->ch = c;
45 q->pre = p;
46 q->next = p->next;
47 p->next = q;
48 p = q;
49 }
50 }
51 first->pre = p; //为了有循环的效果,需要把first节点的pre值置为最后一个节点
52 p->next = first; //最后一个节点的next值置为first节点。53}
5455void solve()
56{
57 node *p = first;
58while(k--)
59 {
60int t = n-1;
61while(t--)
62 {
63 p = p->next;
64 }
65 node *q = p;
66 cout <<q->ch <<"";
67 (q->pre)->next = q->next; //节点删除时,需要注意
68 (q->next)->pre = q->pre; 69 p = q->next;
70 }
71}
72int main()
73{
74 read();
75 solve();
76return0;
77 }

浙公网安备 33010602011771号