最初没仔细读题,case1、5没过,仔细看了看题,真正的题意是:把整个链表以k个结点为一个单位进行reverse。如果剩下结点不足k个,就不用。
#include<bits/stdc++.h>
using namespace std;
typedef struct Node * PtrNode;
struct Node{
int add, data, nadd;
PtrNode next;
};
int n,k,first_add;
map<int,Node> mp;
int main(){
scanf("%d%d%d",&first_add,&n,&k);
for(int i = 0; i < n; ++i){
Node tmp;
scanf("%d%d%d",&tmp.add,&tmp.data,&tmp.nadd);
mp[tmp.add] = tmp;
}
PtrNode head = (PtrNode)malloc(sizeof(Node));
PtrNode p = head;
int next_add = first_add, cnt = 0;
while(next_add != -1){
PtrNode tmp = (PtrNode)malloc(sizeof(Node));
tmp->add = mp[next_add].add;
tmp->data = mp[next_add].data;
tmp->nadd = mp[next_add].nadd;
tmp->next = NULL;
p->next = tmp;
p = p->next;
next_add = p->nadd;
++cnt;
}
PtrNode thead = head;
int t = cnt;
while(cnt >= k){
p = thead->next;
PtrNode pre = thead, q, first = p;
for(int i = 0; i < k; ++i){
q = p->next;
p->next = pre;
p->nadd = pre->add;
pre = p;
p = q;
}
if(t == cnt)
head->next = pre;
thead->next = pre;
thead->nadd = pre->add;
if(p == NULL){
first->next = NULL;
first->nadd = -1;
}
else{
first->next = p;
first->nadd = p->add;
}
thead = first;
cnt -= k;
}
p = head->next;
while(p != NULL){
printf("%05d %d ",p->add,p->data);
if(p->nadd == -1) printf("%d\n",p->nadd);
else printf("%05d\n",p->nadd);
p = p->next;
}
return 0;
}