我的方法:
public ListNode swapPairs(ListNode head) {
ListNode first=head;
ListNode second=null;
if(first!=null&&first.next!=null)//调试错误1:first也可能是空
second=first.next;
else return first;
head=second;
while(first!=null&&second!=null){
ListNode p=second.next;
second.next=first;
first.next=p;
if(p!=null&&p.next!=null){
first.next=p.next;//调试错误2:first的下一个指针也要变化
first=p;
second=first.next;
}else{
return head;
}
}
return head;
}
答案方法:回溯,很精彩
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}