断断续续写了好长时间,卡住了好几次,这个问题还是比较重要的,以后再多看看,理解理解吧。
题目要求:
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.
给出单链表逆转模板代码
List Reverse(List head,int k) //逆转前k个结点,且仅一次
{
List new_=head->next;
List old_=head->next->next;
List temp=old_;
int cnt=1;
while(cnt<k){
temp=old_->next;
old_->next=new_;
new_=old_;
old_=temp;
cnt++;
}
head->next->next=old_;
return new_;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct Node* List;
struct Node
{
int adress;
int data;
int nextadress;
List next;
};
int main()
{
int firstadress,n,k,i;
scanf("%d %d %d",&firstadress,&n,&k);
List L1=(List)malloc(sizeof(struct Node));
List p=L1;
List q1;
L1->next=NULL;
for(i=0;i<n;i++){
q1=(List)malloc(sizeof(struct Node));
scanf("%d %d %d",&q1->adress,&q1->data,&q1->nextadress);
p->next=q1;
p=q1;
}
p->next=NULL;
List L2=(List)malloc(sizeof(struct Node));
L2->next=NULL;
List p2=L2;
int count=0;
int findadress=firstadress;
while(findadress!=-1){
q1=L1;
while(q1->next){
if(q1->next->adress==findadress){
p2->next = q1->next;
q1->next= q1->next->next;
p2 = p2->next;
count++;
findadress=p2->nextadress;
}
else{
q1=q1->next;
}
}
}
p2->next=NULL;
List L3,q3;
L3=(List)malloc(sizeof(struct Node));
List p3=L3;
List tail;
p2=L2;
n=count;
while(n>=k){
n-=k;
for(i=0;i<k;i++){
p3->next=p2->next;
p2->next=p2->next->next;
if(i==0)
tail=p3->next;
else
p3->next->next=q3;
q3=p3->next;
}
p3=tail;
}
p3->next=L2->next;
p3=L3->next;
while(p3->next){
printf("%05d %d %05d\n",p3->adress,p3->data,p3->next->adress);
p3=p3->next;
}
printf("%05d %d -1\n",p3->adress, p3->data);
return 0;
}