给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
这道题之前做过,但是这次还有问题,
if(ne==NULL)
return;
turn函数中的这句话一定要加上 因为如果不加 下面
count=1;
pre=pre1;
pre1=pre1->next;
ne=pre1->next;
ne既然是空指针 你怎么赋值呢 这点一定要注意
还有
nodet *r=pre1;
while(r->next){
count1++;
r=r->next;
}
注意审题
如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
#includetypedef struct node{
int a;
struct node *next;
}nodet;
void creat(nodet *b,int c){
int i;
nodet *flag=b;
for(i=0;inodet *new=(nodet *)malloc(sizeof(nodet));
int d;
scanf("%d",&d);
new->a=d;
new->next=NULL;
flag->next=new;
flag=new;
}
flag->next=NULL;
}
void prin(nodet *b){
nodet *c=b->next;
int s=0;
while(c!=NULL){
printf("%d\t",c->a);
c=c->next;
s++;
}
printf(“now length=%d\n”,s);
}
void turnk(nodet *b,int k){
int count=1;
int count1=1;
nodet *pre=b;
nodet *pre1=pre->next;
nodet *ne=pre1->next;
while(ne){
while(countnext;
pre1->next=ne->next;
ne=ne->next;
pre->next=ss;
ss->next=ss1;
if(ne==NULL)
return;
}
count=1;
pre=pre1;
pre1=pre1->next;
ne=pre1->next;
nodet *r=pre1;
while(r->next){
count1++;
r=r->next;
}
if(count1
}
}
void main(){
nodet *head=(nodet *)malloc(sizeof(nodet));
head->next=NULL;
int num;
printf("input number\n");
scanf("%d",&num);
creat(head,num);
printf("k=\n");
int k;
scanf("%d",&k);
turnk(head,k);
prin(head);
}