The exchange neighbor node list

leetcode Address:

https://leetcode.com/problems/swap-nodes-in-pairs/description/

 

This question is not difficult to see, but in fact the difficulty is moderate, the difficulty is that this problem more intractable boundary conditions, the initial situation will not be possible

 

Here I use a dummy head node to handle the initial situation, the initial situation becomes so unified, that is, with a dummy head node, in the code we do not need to do special handling of the initial situation, but also for the list length of only 1 or 2, a special case of coverage to also cleverly.

 

Code:

 

public class SwapPairs {
public ListNode swapPairs(ListNode head) {
// 虚头结点
ListNode vH=new ListNode(0);
vH.next=head;
ListNode p=vH;
while(p!=null&&p.next!=null&&p.next.next!=null){
ListNode s1=p.next,s2=s1.next,s=s2.next;
p.next=s2;
s2.next=s1;
s1.next=s;
p=s1;
}
return vH.next;
}
}

Guess you like

Origin www.cnblogs.com/zhuge134/p/10926597.html