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 (<= 105) 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
思路:用三个数组分别是data存储数据,list存储地址,next存放下一个结点的地址
输入地址tmp data[tmp]里面存储数据,next[tmp]存放下一个地址
然后结果输入的第一个结点的位置,first,和next数组将链表串起来,存放在list中,并且记载,连起来的链表的长度
while(first!=-1) {
list[sum++]=first;
first=list[first]
}
然后每k个翻转,不足k个就不动 ,最后到不足k的位置上,
for(int i=0;i<(sum-sum%k;i+=k)
{
for(int j=0;j<k/2;j++)
{
交换list[i+j] 和list[i+j+k-j+1]
}
}
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int first,n,k;
scanf("%d %d %d", &first, &n, &k);
int tmp;
int data[100005], next[100005], list[100005];
for (int i = 0; i < n; i++)
{
cin >> tmp;
cin >> data[tmp] >> next[tmp];
}
int sum = 0; //记录有效结点个数
while (first != -1){
list[sum++] = first;
first = next[first];
}
for (int i = 0; i < (sum - sum%k); i += k)
{
//每k个区间翻转一次
for (int j = 0; j < k / 2; j++)
{
int t = list[i+j];
list[i + j] = list[i + k - j-1];
list[i + k - j - 1] = t;
}
}
for (int i = 0; i < sum - 1; i++)
{
printf("%05d %d %05d\n", list[i], data[list[i]], list[i + 1]);
}
printf("%05d %d -1\n", list[sum - 1], data[list[sum - 1]]);
return 0;
}