Java. No pointer. No recursion. No dummy nodes.


  • 0
    M

    As simple as just swapping the value.

    public ListNode swapPairs(ListNode head) {
            
            if (head == null || head.next == null)
                return head;
            
            ListNode runner = head;
            
            while (runner != null && runner.next != null) {
                int temp = runner.val;
                runner.val = runner.next.val;
                runner.next.val = temp;
                runner = runner.next.next;
            }
            
            return head;
        }
    

  • 0

    Yes, your solution works, but you ignored this : "You may not modify the values in the list, only nodes itself can be changed."


Log in to reply
 

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