题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
struct ListNode *pre, *ptr,*p;
struct ListNode * res = (struct ListNode *)malloc(sizeof (struct ListNode));
res->next = head;
pre = NULL;
p = res;
ptr = head;
int len = 0;
while(ptr != NULL){
len++;
ptr = ptr->next;
}
ptr = head;
if(len == 1 || len == 0 || k == 1){
return head;
}else {
for(int i = 1; i <= len/k; i++){
for(int j = 1; j < k; j++){
pre = ptr->next;
ptr->next = pre->next;
pre->next = p->next;
p->next = pre;
}
p = ptr;
ptr = ptr->next;
}
}
return res->next;
}
// write code here
struct ListNode *pre, *ptr,*p;
struct ListNode * res = (struct ListNode *)malloc(sizeof (struct ListNode));
res->next = head;
pre = NULL;
p = res;
ptr = head;
int len = 0;
while(ptr != NULL){
len++;
ptr = ptr->next;
}
ptr = head;
if(len == 1 || len == 0 || k == 1){
return head;
}else {
for(int i = 1; i <= len/k; i++){
for(int j = 1; j < k; j++){
pre = ptr->next;
ptr->next = pre->next;
pre->next = p->next;
p->next = pre;
}
p = ptr;
ptr = ptr->next;
}
}
return res->next;
}