码迷,mamicode.com
首页 > 其他好文 > 详细

1074 Reversing Linked List (25分)

时间:2020-06-17 23:12:36      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:复制   -o   font   link   ted   第一个   ever   sed   ecif   

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 (≤10^5

) which is the total number of nodes, and a positive K (≤N) 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

题目大意:1、first(第一个元素的地址) num(元素的个数) k(每k个元素进行翻转)

     2、输入num个“Address Data Next”类型的元素,以first为首元结点地址,Next为下一个结点地址。生成一个以“-1”为尾元结点的Next的链表后,对链表的每k个元素进行翻转。

 
 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int first, num, k, sum = 0;
 5     cin >> first >> num >> k;
 6     int temp, data[100000], next[100000], addr1[100000], addr2[100000];
 7     for (int i = 0; i < num; i++) {
 8         cin >> temp;
 9         cin >> data[temp] >> next[temp];
10     }
11     while (first != -1) {
12         addr1[sum++] = first;
13         first = next[first];
14     }
15     for (int i = 0; i < sum; i++)  addr2[i] = addr1[i];
16     for (int i = 0; i < (sum - sum % k); i++)  addr2[i] = addr1[i / k * k + k - (1 + i % k)];
17     for (int i = 0; i < sum - 1; i++)
18         printf("%05d %d %05d\n", addr2[i], data[addr2[i]], addr2[i + 1]);
19     printf("%05d %d -1", addr2[sum - 1], data[addr2[sum - 1]]);
20     return 0;
21 }
 

解法: 1、用临时变量temp作为数组指针,把地址为temp的元素数值存入data[temp]中,把temp的元素下一个结点的地址存入next[temp]中,用sum记录链表元素个数。
    2、通过first变量用迭代器的功能实现满足链表顺序的addr1数组
    3、addr1数组经过每k个元素进行翻转变成addr2;
      *先把addr1数组复制成addr2数组;
      *再对(sum-sum%k)(即满足翻转要求的前x组元素)个元素进行翻转,其中:1/k*k(欲翻转元素i前面的整组元素个数,也就是该组的第一个地址)、k - (1 + i % k)(每组翻转前i应该对应加的几个地址)

 

1074 Reversing Linked List (25分)

标签:复制   -o   font   link   ted   第一个   ever   sed   ecif   

原文地址:https://www.cnblogs.com/i-chase/p/13154997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!