7-2 Block Reversing (25分)
Given a singly linked list L. Let us consider every K nodes as a block (if there are less than K nodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to reverse all the blocks in L. For example, given L as 1→2→3→4→5→6→7→8 and K as 3, your output must be 7→8→4→5→6→1→2→3.
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 size of a block. 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 8 3
71120 7 88666
00000 4 99999
00100 1 12309
68237 6 71120
33218 3 00000
99999 5 68237
88666 8 -1
12309 2 33218
Sample Output:
71120 7 88666
88666 8 00000
00000 4 99999
99999 5 68237
68237 6 00100
00100 1 12309
12309 2 33218
33218 3 -1
题目描述:反转链表
输入:第一行head、n、k分别表示链表的头结点起始地址,n个结点,每k个结点为一组反转。
输出:输出反转后的链表。
常规题,先将链表串联起来,算出有多少组,从索引最大的一组开始链接,就能将链表反转了。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
struct node{
int head, num, next;
}l1[maxn];
vector<node> v1, v2;
int main()
{
int head, n, k;
node t;
scanf("%d %d %d", &head, &n, &k);
for(int i=0; i<n; i++){
scanf("%d %d %d", &t.head, &t.num, &t.next);
l1[t.head] = t;
}
while(head!=-1){
t = l1[head];
v1.push_back(t);
head = t.next;
}
int cnt = v1.size()/k;
while(cnt>=0){
for(int j=0; j<k&&cnt*k+j<v1.size(); j++){
v2.push_back(v1[cnt*k+j]);
}
cnt--;
}
for(int i=0; i<v2.size()-1; i++){
t = v2[i];
printf("%05d %d %05d\n", t.head, t.num, v2[i+1].head);
}
printf("%05d %d -1\n", v2[v2.size()-1].head, v2[v2.size()-1].num);
return 0;
}