Concise Java Solution with FakeHead


  • 0
    M
    public ListNode swapPairs(ListNode head) {
    
    	ListNode fakeHead = new ListNode(-1);
    
    	fakeHead.next = head;
    	head = fakeHead;
    	ListNode swap1, swap2, next;
    	while (head.next != null && head.next.next != null) {
    		swap1 = head.next;
    		swap2 = swap1.next;
    		next = swap2.next;
    		head.next = swap2;
    		swap2.next = swap1;
    		swap1.next = next;
    	    head = swap1;
    	}
    
    	return fakeHead.next;
    }

Log in to reply
 

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