Java O(1) space


  • 0
    A
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode dummy = new ListNode(0);
            ListNode node = head;
            ListNode previous = dummy;
            ListNode pairFirst = null;
            ListNode pairSecond = null;
            while (node != null && node.next != null) {
                ListNode savedNext = node.next.next;
                pairSecond = node;
                pairFirst = node.next;
                pairFirst.next = pairSecond;
                previous.next = pairFirst;
                previous = pairSecond;
                node = savedNext;
            }
            pairSecond.next = node;
            return dummy.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.