LeetCode 解题思路 15(Hot 100)-Java代码:

时间:2025-03-14 20:21:17
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode prevEnd = dummy;
        ListNode first = prevEnd.next;
        ListNode second = first.next;

        while (first != null && second != null) {
            ListNode nextNode = second.next;
            
            prevEnd.next = second;
            second.next = first;
            first.next = nextNode;

            prevEnd = first;
            first = prevEnd.next;
            if (first == null) break;
            second = first.next;
            if (second == null) break;
        }

        return dummy.next;
    }
}