先看一眼题:
草稿纸上画个图,就知道指针该怎么连了,草稿纸太乱了,就不贴了,直接上代码吧:
public static ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
if(head.next.next==null){
head.next.next=head;
ListNode p = head.next;
head.next=null;
return p;
}
ListNode p=null,q=null,r=null,pre=null,res=null;
boolean first = true;
p=head;
q=p.next;
r=q.next;
while (q!=null){
q.next=p;
p.next=r;
if(pre!=null)
pre.next=q;
try {
r = r.next;
}catch (NullPointerException e){
r=null;
}
pre=q;
if(first){
res =pre;
first=false;
}
q=p.next;
try {
r = r.next;
}catch (NullPointerException e){
r=null;
}
try {
q = q.next;
}catch (NullPointerException e){
q=null;
}
p=p.next;
pre=pre.next;
}
return res;
}