原题链接在这里:https://leetcode.com/problems/reverse-nodes-in-k-group/
题目:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
题解:
检测list长度len, 用此长度除以k, 得到的就是需要roate的次数.
这类内部rotate都需要标记前一个点 用以连接rotate后的那段head, 这个标记记为mark. 有些需要从原有list 的head开始rotate, 所以需要create一个dunmy, dunmy.next = head.
内部roate时与Reverse Linked List的method 2 相同。每次tail = mark.next, cur = tail在循环中重复更新, 旋转一 次直到 k次(Here, there is no need to check if tail.next = null, 因为之前有rotateTimes的限制). 每次rotateTimes is decreased by one, until 0.
为什么是到i从1而不是0开始呢. e.g. k=3是说三个node reverse, 其实只需要reverse 2次而不是3次.
Time Complexity: O(n), n是list长度. Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseKGroup(ListNode head, int k) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode mark = dummy; 18 int len = 0; 19 while(mark.next != null){ 20 mark = mark.next; 21 len++; 22 } 23 24 mark = dummy; 25 int rotateTimes = len/k; 26 while(rotateTimes > 0){ 27 ListNode tail = mark.next; 28 ListNode cur = tail; 29 ListNode pre; 30 ListNode temp; 31 32 int i = 1; 33 while(i<k){ 34 pre = cur; 35 cur = tail.next; 36 temp = cur.next; 37 cur.next = pre; 38 tail.next = temp; 39 i++; 40 } 41 42 mark.next = cur; 43 mark = tail; 44 rotateTimes--; 45 } 46 47 return dummy.next; 48 } 49 }