My simple JAVA solution, constant space, easy understanding


  • 0
    Y

    I think it will be helpful if you draw a little listnode graph for this problem.

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode current = new ListNode(Integer.MAX_VALUE);
            current.next = head;
            ListNode dummy = current;
            while(dummy.next !=null && dummy.next.next != null){
                ListNode temp = dummy.next.next;
                dummy.next.next = temp.next;
                temp.next = dummy.next;
                dummy.next = temp;
                dummy = dummy.next.next;
            }
            return current.next;
        }
    }
    

Log in to reply
 

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