LeetCode:24 两两交换链表中的节点

76 阅读2分钟

「这是我参与2022首次更文挑战的第24天,活动详情查看:2022首次更文挑战

题目

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)

示例 1:

img

输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100

解题

解题一:递归

思路

对链表进行递归处理,每两个节点组成一个交换,从链表结尾开始反向递归填充元素

代码

/**
 * Definition for singly-linked list.
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            // null 或者只有一个元素,直接返回
            return head;
        }
        // 节点交换
        ListNode tempNode = head.next;
        head.next = swapPairs(tempNode.next);
        tempNode.next = head;
        return tempNode;
    }
}

总结

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
  • 执行用时:0 ms,在所有 Java 提交中击败了 100% 的用户
  • 内存消耗:35.9 MB,在所有 Java 提交中击败了 76.96% 的用户

解题二:迭代

思路

代码

/**
 * Definition for singly-linked list.
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode nextHead = head.next;
        ListNode tailNode = head;
        tailNode.next = nextHead.next;
        nextHead.next = head;
        ListNode result = nextHead;
        while (tailNode != null && tailNode.next != null) {
            tailNode = tailNode.next;
            nextHead = tailNode.next;
            tailNode.next = nextHead.next;
            nextHead.next = tailNode;
        }
        return result;
    }

    // 合并头节点的特殊处理
    public static ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode result = null;
        ListNode tempNode;
        ListNode nextHead;
        ListNode tailNode = head;
        while (tailNode.next != null && tailNode.next.next != null) {
            tempNode = tailNode == head && result ==null? head :tailNode.next;
            tailNode.next = tailNode == head && result ==null?  tailNode.next :tailNode.next.next;
            tailNode = tempNode;
            nextHead = tempNode.next;
            tailNode.next = nextHead.next;
            nextHead.next = tailNode;
            if (result == null) {
                result = nextHead;
            }
        }
        return result;
    }
}

总结

性能分析

  • 执行耗时:0 ms,击败了 100.00% 的 Java 用户
  • 内存消耗:39.1 MB,击败了 12.52% 的 Java 用户