24 两两交换链表

45 阅读1分钟

一.题目

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

示例 1:

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

二.代码

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)   return head;
        ListNode cur = new ListNode(-1, head);
        ListNode now = cur;
        // 这个判断循环的是关键
        while(now.next != null && now.next.next != null) {  
            ListNode a = now.next;
            ListNode b = now.next.next;
            now.next = b;
            a.next = b.next;
            b.next = a;
            now = a;
        }
        return cur.next;
    }
}