24. 两两交换链表中的节点

image.png

题解

递归解法

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:39.2 MB, 在所有 Java 提交中击败了21.37%的用户

  1. public class Solution {
  2. public ListNode swapPairs(ListNode head) {
  3. // 递归终止:如果只有一个节点|奇数节点|偶数节点,已经交换完成
  4. if (head == null || head.next == null) return head;
  5. // 存放下一个节点
  6. ListNode next = head.next;
  7. // 下一对交换返回的头节点
  8. head.next = swapPairs(next.next);
  9. next.next = head;
  10. return next;
  11. }
  12. }

迭代解法

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:39.3 MB, 在所有 Java 提交中击败了9.38%的用户

  1. // 使用 pre 存放前置节点,n1 存放 pre 的下个节点,n2 存放 pre 的下下个节点
  2. // 每次遍历都交换 n1 和 n2 的位置
  3. // 由于第一个节点没有前置节点,所以自己创建一个节点作为 head 的前置节点
  4. // 遍历终于条件是 pre 的下个和下下个节点都不为空。
  5. // 为什么遍历终止条件要求 pre 下下节点不为空?因为链表长度为奇数时最后一个节点不需要交换
  6. class Solution {
  7. public ListNode swapPairs(ListNode head) {
  8. ListNode temp = new ListNode(0);
  9. temp.next = head;
  10. ListNode pre = temp;
  11. while(pre.next != null && pre.next.next != null) {
  12. ListNode n1 = pre.next;
  13. ListNode n2 = pre.next.next;
  14. n1.next = n2.next;
  15. n2.next = n1;
  16. pre.next = n2;
  17. pre = n1;
  18. }
  19. return temp.next;
  20. }
  21. }