题目

image.png

思路

  • 思路一:使用头插法来翻转节点
  • 思路二:使用递归翻转链表

    代码

    1. public ListNode swapPairs(ListNode head) {
    2. ListNode dummy = new ListNode(0);
    3. dummy.next = head;
    4. ListNode prv = dummy;
    5. while (head != null && head.next != null) {
    6. ListNode nex = head.next;
    7. head.next = nex.next;
    8. nex.next = prv.next;
    9. prv.next = nex;
    10. //重置节点
    11. prv = head;
    12. head = head.next;
    13. }
    14. return dummy.next;
    15. }
    16. //自己的递归
    17. public ListNode swapPairs(ListNode head) {
    18. if (head == null || head.next == null) return head;
    19. ListNode nextHead = swapPairs(head.next.next);
    20. ListNode nHead = reverse(head, 1);
    21. nHead.next.next = nextHead;
    22. return nHead;
    23. }
    24. public ListNode reverse(ListNode head, int i) {
    25. if (i == 2) {
    26. return head;
    27. }
    28. ListNode nHead = reverse(head.next, i + 1);
    29. head.next.next = head;
    30. head.next = null;
    31. return nHead;
    32. }
    33. //别人的递归
    34. public ListNode swapPairs(ListNode head) {
    35. if (head == null || head.next == null) return head;
    36. ListNode next = head.next;
    37. head.next = swapPairs(head.next.next);
    38. next.next = head;
    39. return next;
    40. }

    两两交换链表中的节点