题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ #include <stdlib.h> struct ListNode* revers(struct ListNode* head, int m, int n) { struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode)); res->next = head; if (head == NULL || m == n) { return head; } else { struct ListNode* pre = res; struct ListNode* cur = pre->next; struct ListNode* post = NULL; for (int i = 1; i < m; i++) { pre = pre->next; } cur = pre->next; for (int i = m; i < n; i++) { post = cur->next; cur->next = post->next; post->next = pre->next; pre->next = post; } return res->next; } } struct ListNode* reverseKGroup(struct ListNode* head, int k ) { // write code here struct ListNode*p=head; int i=0; while(p!=NULL){ i++; p=p->next; } if(k>i){ return head; } for(int n=1;n<i;n=n+k){ if(n+k-1>i){ break; } head=revers(head,n,n+k-1); } return head; }