Skip to content
本页目录

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

https://leetcode.cn/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

思路

  1. 设置 dummyHead,返回 dummyHead.next
  2. 检测 cur 和 cur.next 不为空的时候,使用临时节点进行交换

参考代码

csharp
public class Solution {
    public ListNode SwapPairs(ListNode head) {
    	ListNode dummyHead = new ListNode();
    	dummyHead.next = head;
    	ListNode cur = head;
    	ListNode pre = dummyHead;

    	while(cur != null && cur.next != null){
            //交换
    		ListNode temp = cur.next.next;
    		pre.next = cur.next;
    		cur.next.next = cur;
    		pre.next.next = cur;
    		cur.next = temp;
    		//下移
            pre = cur;
    		cur = cur.next;
    	}

    	return dummyHead.next;
    }
}

复习:20220511

同上,代码略有调整,cur表示头指针

csharp
public class Solution {
    public ListNode SwapPairs(ListNode head) {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode cur = dummyHead;
        while(cur != null && cur.next != null && cur.next.next != null){
            ListNode next1 = cur.next;
            ListNode next2 = cur.next.next;

            next1.next = next2.next;
            cur.next = next2;
            next2.next = next1;

            cur = cur.next.next;
        }
        return dummyHead.next;
    }
}

Released under the MIT License.