1->2->3->4->5 ==》 2->1->4->3->5
非递归求解
public ListNode swapPairs(ListNode head) {
if (head==null||head.next==null) return head;
ListNode pre=new ListNode(0);
pre.next=head;
ListNode temp=pre;
while (temp.next!=null&&temp.next.next!=null){
ListNode start=temp.next;
ListNode end=temp.next.next;
temp.next=end;
start.next=end.next;
end.next=start;
temp=start;
}
return pre.next;
}
递归求解
/**
* 递归求解
* @return
*/
public ListNode swapPairs2(ListNode head){
if (head==null||head.next==null) return head;
ListNode nextNode=head.next;
head.next=swapPairs(nextNode.next);
nextNode.next=head;
return nextNode;
}