题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here if (k == 1) { return head; } if (head == null || head.next == null) { return head; } int times = 0; ListNode temp; ListNode op = new ListNode(-1), tmp; op.next = head; tmp = op; while (head.next != null) { temp = head.next; head.next = temp.next; temp.next = tmp.next; tmp.next = temp; times++; if (times % (k - 1) == 0) { tmp = head; if(tmp.next!=null){ head=tmp.next; } else{ return op.next; } } } if (times % (k - 1) != 0) { head=tmp.next; while (head.next != null) { temp = head.next; head.next = temp.next; temp.next = tmp.next; tmp.next = temp; } } return op.next; } }
1、对于我来说,难点不在于如何反转,而在于一些临界值的处理,对可能出现null地方需要考虑增加临界值的处理。
2、核心部分在于循环不变式的构建,
类似于头插法,不变的是:头head,指向该次反转的tmp,因为要改变head的next、tmp的next,因此需要一个临时变量存储head的next。每次循环都是源于这三个“不变”变量的更改。
3、k值反转,实际上反转k-1次。