List习题Reversing Linked List

Posted pennyxia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了List习题Reversing Linked List相关的知识,希望对你有一定的参考价值。

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤) which is the total number of nodes, and a positive K (≤) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

思路(使用数组调整结点输出顺序):

  • 题目给出结点的格式Address data next ,其中Address是结点的地址,data是数据域,next是下一个结点的地址;
  • 由于结点的Address具有唯一标志性,所以思考将Address和data,next联系起来,所以定义Data[Address]和Next[Address];
  • 定义List[Address]记录链表的顺序,然后对其进行分组翻转,改变结点的输出顺序
  • 注意:可能存在无效结点,不加判断的话最后一个测试点错误

 

 1 // A1074.cpp 
 2 //
 3 #include <stdio.h>
 4 const int MAX = 100005;
 5 int Data[MAX], Next[MAX],List[MAX];
 6 
 7 int main()
 8 {
 9     int FirAdd, n, k;
10     scanf("%d%d%d", &FirAdd, &n, &k);
11     for (int i = 0; i < n; i++) {
12         int tmpAdd, tmpData, tmpNext;
13         scanf("%d%d%d", &tmpAdd, &tmpData, &tmpNext);
14         Data[tmpAdd] = tmpData;
15         Next[tmpAdd] = tmpNext;
16     }
17     //从FirAddres开始将所有结点地址串起来
18     int idx = 0;
19     while (FirAdd != -1) {
20         List[idx++] = FirAdd;
21         FirAdd = Next[FirAdd];
22     }
23     //将串好的地址List进行分组翻转
24     for (int i = 0; i<idx-idx%k; i += k) {
25         //对称性翻转
26         for (int j = 0; j < k / 2;j++) {
27             int tmp = List[i + j];
28             List[i + j] = List[i + k -j- 1];
29             List[i + k -j- 1] = tmp;
30         }
31     }
32     //输出
33     //printf("
");
34     for (int i = 0; i < idx-1; i++) {
35         printf("%05d %d %05d
", List[i], Data[List[i]], List[i+1]);
36     }
37     //最后一个结点
38     printf("%05d %d -1
", List[idx-1], Data[List[idx-1]]);
39     return 0;
40 }

 

以上是关于List习题Reversing Linked List的主要内容,如果未能解决你的问题,请参考以下文章

02-线性结构3 Reversing Linked List

Reversing Linked List

1074 Reversing Linked List (25)

1074. Reversing Linked List (25)

1074. Reversing Linked List (25)

1074. Reversing Linked List (25)