154 字 少于 1 分钟阅读

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

img

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

示例 2:

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

示例 3:

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

提示:

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

进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)

思路

如同反转链表一样,两个两个的反转。

迭代

public ListNode swapPairs(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    // 虚拟头结点
    ListNode pHead = new ListNode();
    pHead.next = head;
    ListNode pre = pHead;
    ListNode next;
    
    while (head != null && head.next != null) {
        next = head.next;
        pre.next = next;
        head.next = next.next;
        next.next = head;
        pre = head;
        head = head.next;
    }
    return pHead.next;
}

递归

链表 1 -> 2 -> 3 -> 4 -> 5 ->6

假设节点 2 递归后为 1 -> 2 -> 4 -> 3 -> 6 -> 5

递归返回后的节点为 4,那么只需要反转1、2两个节点并和 4 节点连接在一起即可。

 public ListNode swapPairs(ListNode head) {
     if(head == null || head.next == null){
         return head;
     }
     ListNode newHead = head.next;
     head.next = swapPairs(newHead.next);
     newHead.next = head;
     return newHead;
 }