例如:链表:1->2->3->4->5->6->7->8->null, K = 3。调整后:3->2->1->6->5->4->7->8->null。
其中 7,8不调整,因为不够一组。
LeetCode25,这里用的是分别递归的思想:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | public ListNode reverseKGroup(ListNode head, int k) {
 ListNode tail = head;
 for (int i = 1; i < k && tail != null; i++) {
 tail = tail.next;
 }
 if(tail == null)
 return head;
 
 ListNode t2 = tail.next;
 tail.next = null;
 
 
 ListNode newHead = reverseList(head);
 
 ListNode nextNewHead = reverseKGroup(t2, k);
 
 
 ListNode newTail = head;
 newTail.next = nextNewHead;
 
 return newHead;
 }
 
 
 
 private static ListNode reverseList(ListNode head) {
 if(head == null || head.next == null)
 return head;
 ListNode result = reverseList(head.next);
 head.next.next = head;
 head.next = null;
 return result;
 }
 
 |