原题链接在这里:https://leetcode.com/problems/reverse-nodes-in-k-group/
思路: 1. 检测list长度,用此长度除以k,得到的就是需要roate的次数,记为rotNum,如果rotNum等于0,则不需要rotate,直接 返回head .
2. 这类内部rotate都需要标记前一个点,用以连接rotate后的那段head,这个标记记为mark。有些需要从原有list 的head开 始rotate,所以需要create一个dunmy, dunmy.next = head.
3. 内部roate时与Reverse Linked List的method 2 相同。每次tail = mark.next, cur = tail在循环中重复更新,旋转一 次,k--知道k>1(Here, there is no need to check if tail.next = null, 因为之前有rotNum的限制). 每次rotNum is decreased by one, until 0.
Note: 在生成dunmy时注意 new ListNode(0), 这部分不能省略。
AC Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null || k < 2){
return head;
}
int i = 0;
ListNode tail = head;
while(tail != null){
i++;
tail = tail.next;
}
int rotNum = i/k;
int numK = k;
if(rotNum == 0){
return head;
}
ListNode dunmy = new ListNode(0); //error
dunmy.next = head;
ListNode mark = dunmy;
while(rotNum>0){
tail = mark.next;
ListNode cur = tail;
ListNode pre;
ListNode temp;
while(k > 1){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
k--;
}
mark.next = cur;
mark = tail;
tail = mark.next;
cur = tail;
k = numK;
rotNum--;
}
return dunmy.next;
}
}