25. Reverse Nodes in k-Group

k个一组反转链表

  1. public ListNode reverseKGroup(ListNode head, int k) {
  2. ListNode hair = new ListNode(0);
  3. hair.next = head;
  4. ListNode pre = hair;
  5. while (head != null) {
  6. ListNode tail = pre;
  7. // 查看剩余部分长度是否大于等于 k
  8. for (int i = 0; i < k; ++i) {
  9. tail = tail.next;
  10. if (tail == null) {
  11. return hair.next;//
  12. }
  13. }
  14. ListNode nex = tail.next;
  15. ListNode[] reverse = myReverse(head, tail);
  16. head = reverse[0];
  17. tail = reverse[1];
  18. // 把子链表重新接回原链表
  19. pre.next = head;
  20. tail.next = nex;
  21. pre = tail;
  22. head = tail.next;
  23. }
  24. return hair.next;
  25. }
  26. public ListNode[] myReverse(ListNode head, ListNode tail) {
  27. ListNode prev = tail.next;//
  28. ListNode p = head;
  29. while (prev != tail) {
  30. ListNode nex = p.next;
  31. p.next = prev;
  32. prev = p;
  33. p = nex;
  34. }
  35. return new ListNode[]{tail, head};
  36. }
  37. 作者:LeetCode-Solution
  38. 链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/k-ge-yi-zu-fan-zhuan-lian-biao-by-leetcode-solutio/