My simple java sulotion


  • 0
    S

    I add an extra Node in front of the head ,so I can deal the Nodes every three in the same way.Here is the code

    public ListNode swapPairs(ListNode head) {
            if(head.next ==null)
            	return head;
            ListNode pre = new ListNode(-1);
            pre.next = head;
            ListNode current = pre;
            while(current.next!=null && current.next.next!=null){
            	ListNode temp = current.next;
            	current.next = temp.next;
            	temp.next = current.next.next;
            	current.next.next = temp;
            	current = current.next.next;
            }
            return pre.next;
        }
    

Log in to reply
 

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