Swap Nodes in Pairs

原题:

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

此题就是一个链表节点的交换,不过要注意边界条件


public ListNode swapPairs(ListNode head) {
        if(head == null)
        	return null;
        ListNode tempHead = new ListNode(0);
        tempHead.next = head;
        ListNode pPre = head;
        ListNode pAft = tempHead;
        while(pPre != null && pPre.next != null) {	//注意这里的边界条件
        	pAft.next = pPre.next;
        	pPre.next = pPre.next.next;
        	pAft.next.next = pPre;
        	
        	pPre = pPre.next;
        	pAft = pAft.next.next;
        }
        return tempHead.next;
    }




你可能感兴趣的:(Swap Nodes in Pairs)