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.
#include <stdio.h>
#include <stdlib.h>
typedef struct node * List;
struct node{
long thisposition;
int data;
long nextposition;
struct node * next;
};
static long N,K;
List readlist();
void attach(long thisposition,int data,long nextposition,List * prear);
void insert(List p,long thisposition,int data,long nextposition);
List reversedlist(List L,long N,long K);
void printp(List L);
int main()
{
List L;
L=readlist();
// printp(L);
List revL=reversedlist(L,N,K);
// putchar('\n');
printp(revL);
return 0;
}
List readlist()
{
extern long N,K;
List L=(List)malloc(sizeof(struct node));L->next=NULL;
List rear=L;
long thisposition;
scanf("%ld %ld %ld",&thisposition,&N,&K);
struct node array[N];
for(int i=0;i<N;i++){
scanf("%ld %d %ld",&array[i].thisposition,&array[i].data,&array[i].nextposition);
}
while(thisposition!=-1){
for(int i=0;i<N;i++){
if(array[i].thisposition==thisposition){
attach(array[i].thisposition,array[i].data,array[i].nextposition,&rear);
thisposition=array[i].nextposition;
break;
}
}
}
List temp=L;
L=L->next;
free(temp);
return L;
}
void attach(long thisposition,int data,long nextposition,List * prear)
{
List att=(List)malloc(sizeof(struct node));att->next=NULL;
(*prear)->next=att;(*prear)=(*prear)->next;
(*prear)->thisposition=thisposition;(*prear)->data=data;(*prear)->nextposition=nextposition;
}
void insert(List insL,long thisposition,int data,long nextposition)//在insL指向的节点后面插入节点
{
List inst=(List)malloc(sizeof(struct node));inst->next=NULL;
inst->thisposition=thisposition;inst->data=data;inst->nextposition=nextposition;
inst->next=insL->next;insL->next=inst;
}
List reversedlist(List L,long N,long K)
{
List revL=(List)malloc(sizeof(struct node));revL->next=NULL;
long time=N/K;
List rear=L;
List insL=revL;
for(;time;time--){
for(int i=0;i<K;i++){
insert(insL,rear->thisposition,rear->data,rear->nextposition);
rear=rear->next;
}
while(insL->next) insL=insL->next;
}
while(rear){
insert(insL,rear->thisposition,rear->data,rear->nextposition);
insL=insL->next;
rear=rear->next;
}
for(List t=revL->next;t;t=t->next){
if(t->next)
t->nextposition=t->next->thisposition;
else
t->nextposition=-1;
}
List temp=revL;
revL=revL->next;
free(temp);
return revL;
}
void printp(List L)
{
while(L){
if(L->next){
printf("%.5ld %d %.5ld\n",L->thisposition,L->data,L->nextposition);
}else {
printf("%.5ld %d %ld",L->thisposition,L->data,L->nextposition);
}
L=L->next;
}
}
测试点5、6还不知道什么原因呜呜呜