1074. Reversing Linked List (25)
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, andNext 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 33218Sample Output:
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
1.开头的思路,又是排序,又是反转,弄得很凌乱。
2,看了别人的思路,一个是vector的数组可以开得很大,一个是完全可以用vector的索引当做地址,这样速度会 变快。
3.先把顺序理顺了,然后再反着输出,就比较方便了。
4.那个最后顺序输出不一定是n个,所以最好用-1来判断结尾。
5.还有两个测试点。
6.处理了K=2的情况,啊啊啊,还是有两个测试点,
***重新做的
1.看别人的做法,第一,先把数据存入vector,把vector设得很大,这样就不用搜索了。
2.按照顺序列出一个vector b 是针对Input的顺序,
3.再开一个vector 这样再反转b
//#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<vector>
#include<map>
#include<iomanip>
using namespace std;
struct NODE{
int fadd;
int num;
int radd;
};
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
#endif
int fstadd,N,K;
vector <NODE> a(100000);
cin>>fstadd>>N>>K;
int i;
//input
for(i=0;i<N;i++){
NODE tt;
scanf("%d%d%d",&tt.fadd,&tt.num,&tt.radd);
a[tt.fadd]=tt;
}
//sort
vector<NODE> b;
while(fstadd!=-1){
b.push_back(a[fstadd]);
fstadd=a[fstadd].radd;
}
//cout
int cc=0;
bool ff=true;
vector <NODE> c;
while(cc+K<=b.size()){
int k=K;
while(k--){
c.push_back(b[cc+k]);
}
cc+=K;
}
while(cc<b.size()){
c.push_back(b[cc]);
cc++;
}
cc=0;
while(cc<c.size()){
if(cc==0){
printf("%05d %d ",c[cc].fadd,c[cc].num);
}else{
printf("%05d\n%05d %d ",c[cc].fadd,c[cc].fadd,c[cc].num);
}
cc++;
}
cout<<"-1";
fclose(stdin);
system("pause");
return 0;
}