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
solution:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const int maxn=1e5+5;
int main()
{
int start,n,k;
cin>>start>>n>>k;
int data[maxn],next[maxn];
int cnt=0;
for(int i=0;i<n;i++)
{
int tmp;cin>>tmp;
cin>>data[tmp]>>next[tmp];
}
vector<pair<int,int> >list;
while(start!=-1)
{
cnt++;
list.push_back({start,data[start]});
start=next[start];
}
vector<pair<int,int> >ans;
if(cnt<=k)
{
ans=list;
}
else
{
int tmp=cnt%k;
if(tmp)
for(int i=cnt-tmp;i<cnt;i++)
{
ans.push_back({list[i].first,list[i].second});
}
cnt-=tmp;
for(int i=cnt-k;i>=0;i-=k)
{
for(int j=0;j<k;j++)
{
ans.push_back({list[i+j].first,list[i+j].second});
//cout<<i+j<<endl;
}
}
}
//cout<<list[2].first<<' '<<list[2].second;
for(int i=0;i<ans.size()-1;i++)
{
printf("%05d %d %05d\n",ans[i].first,ans[i].second,ans[i+1].first);
}
printf("%05d %d -1\n",ans[ans.size()-1].first,ans[ans.size()-1].second);
}