美文网首页
0024. 两两交换链表中的节点

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

作者: 蓝笔头 | 来源:发表于2021-08-17 09:58 被阅读0次

题目地址

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

题目描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:
输入: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) {
        // 假设 swapPairs(head) 是已经交换好的链表
        // 因此有:
        // swapPairs(1 -> 2 -> 3 -> 4 -> 5)
        // 2 -> 1 -> swapPairs(3 -> 4 -> 5)

        // base case 1:没有节点
        if (head == null) {
            return null;
        }
        // base case 2:只有一个节点
        if (head.next == null) {
            return head;
        }
        
        // 交换节点
        // 交换前:head -> head.next -> head.next.next
        // 交换后:head.next -> head -> head.next.next
        ListNode newHead = head.next;
        head.next = newHead.next;
        newHead.next = head;

        // 递归调用
        // 交换后的 head.next 就是交换前的 head.next.next
        head.next = swapPairs(head.next);
        return newHead;
    }
}

时间复杂度:O(n),n 为链表的长度。

相关文章

网友评论

      本文标题:0024. 两两交换链表中的节点

      本文链接:https://www.haomeiwen.com/subject/nvzmbltx.html