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 (≤10e5) 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
思路&分析
pat传统链表题,近来几次机试,考试第二题都是这东西,都是一样的做法,输入的时候做一个adress
到序号的映射,实现根据地址查节点,按next
地址遍历静态链表,再按题目要求来反转输出。
注意点:
- 老坑点了,题目没明说,给的样例也没体现出来,是会有测试样例存在输入数据的节点不在链上的,必须从头遍历一遍,重新算出链表长度。【貌似99分的人都是这题24分…】
提交代码(AC)
#include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
#include <map>
#include <string>
#include <algorithm>
#define INF 0x3fffffff
using namespace std;
struct node{
int adr,data,next;
node(int a,int d,int n){adr=a;data=d;next=n;}
};
int main()
{
// freopen("1.txt","r",stdin);
int f,num,k;
cin>>f>>num>>k;
int ta,tb,tc;
int book[100001]={0};
vector<node> all;
for(int i=0;i<num;i++){
scanf("%d%d%d",&ta,&tb,&tc);
all.push_back(node(ta,tb,tc));
book[ta]=i;
}
vector<node> l,res;
while(f!=-1){
l.push_back(all[book[f]]);
f=all[book[f]].next;
}
int len=l.size();
int gnum=(len+k-1)/k;
for(int i=gnum-1;i>=0;i--){
int mx=(i+1)*k>len?len:(i+1)*k;
for(int j=i*k;j<mx;j++){
res.push_back(l[j]);
}
}
for(int i=0;i<res.size()-1;i++){
printf("%05d %d %05d\n",res[i].adr,res[i].data,res[i+1].adr);
}
printf("%05d %d -1",res[res.size()-1].adr,res[res.size()-1].data);
return 0;
}