题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
- 虚拟表头,始终指向头节点
- 计算链表长度,不反转后续不成组部分
-
分组反转,类似固定区间反转链表,每次分组结束需调整指针
public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { ListNode res = new ListNode(-1);//虚假表头,指向头节点 res.next = head; ListNode pre = res,cur = head,temp; int count = 0; while(head != null){ //计算链表长度 count++; head = head.next; } count = count/k * k; //需反转区域,隔离不成组部分 for(int i=1; i<count; i++){ if(i%k == 0){//开启下一轮反转 pre = cur; cur = cur.next; continue; } temp = cur.next; cur.next = temp.next; temp.next = pre.next; pre.next = temp; } return res.next; } }