image.png

解题思路

用栈,我们把 k 个数压入栈中,然后弹出来的顺序就是翻转的!

这里要注意几个问题:

第一,剩下的链表个数够不够 k 个(因为不够 k 个不用翻转);

第二,已经翻转的部分要与剩下链表连接起来。

  1. public ListNode reverseKGroup(ListNode head, int k) {
  2. Deque<ListNode> stack = new ArrayDeque<ListNode>();
  3. ListNode dummy = new ListNode(0);
  4. ListNode p = dummy;
  5. while (true) {
  6. int count = 0;
  7. ListNode tmp = head;
  8. while (tmp != null && count < k) {
  9. stack.add(tmp);
  10. tmp = tmp.next;
  11. count++;
  12. }
  13. if (count != k) {
  14. p.next = head;
  15. break;
  16. }
  17. while (!stack.isEmpty()){
  18. p.next = stack.pollLast();
  19. p = p.next;
  20. }
  21. p.next = tmp;
  22. head = tmp;
  23. }
  24. return dummy.next;
  25. }


image.png

  1. public ListNode reverseKGroup(ListNode head, int k) {
  2. ListNode dummy = new ListNode(0);
  3. dummy.next = head;
  4. ListNode pre = dummy;
  5. ListNode tail = dummy;
  6. while (true) {
  7. int count = 0;
  8. while (tail != null && count != k) {
  9. count++;
  10. tail = tail.next;
  11. }
  12. if (tail == null) break;
  13. ListNode head1 = pre.next;
  14. while (pre.next != tail) {
  15. ListNode cur = pre.next;
  16. pre.next = cur.next;
  17. cur.next = tail.next;
  18. tail.next = cur;
  19. }
  20. pre = head1;
  21. tail = head1;
  22. }
  23. return dummy.next;
  24. }

递归

 public ListNode reverseKGroup(ListNode head, int k) {
        ListNode cur = head;
        int count = 0;
        while (cur != null && count != k) {
            cur = cur.next;
            count++;
        }
        if (count == k) {
            cur = reverseKGroup(cur, k);
            while (count != 0) {
                count--;
                ListNode tmp = head.next;
                head.next = cur;
                cur = head;
                head = tmp;
            }
            head = cur;
        }
        return head;
    }