LeetCode 24. Swap Nodes in Pairs

LeetCode 24. Swap Nodes in Pairs (两两交换链表中的节点)

题目

链接

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

问题描述

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

示例

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

提示

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

思路

遍历,交换,需要注意到的是注意节点的变化,不要少了某个节点没考虑到。同时采用虚拟头结点,减少操作。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(1)

代码

Java

    public ListNode swapPairs(ListNode head) {
        ListNode tmphead = new ListNode();
        tmphead.next = head;
        ListNode  pre = tmphead;
        //tp0 1 tmp2 3 4
        while (pre.next != null && pre.next.next != null) {
            ListNode tmp = pre.next.next;
            pre.next.next = tmp.next;
            tmp.next = pre.next;
            pre.next =tmp;
            pre = pre.next.next;
        }
        return tmphead.next;
    }
posted @ 2022-05-18 15:33  cheng102e  阅读(23)  评论(0编辑  收藏  举报