方法一:非递归
public ListNode swapPairs(ListNode head){
ListNode res=new ListNode(0);
res.next=head;
ListNode cur=res;
while (cur.next!=null&&cur.next.next!=null){
ListNode start=cur.next;
ListNode end=cur.next.next;
cur.next=end;
start.next=end.next;
end.next=start;
cur=start;
}
return res.next;
}
方法二:递归
public ListNode swapPairs(ListNode head){
if(head==null||head.next==null) return head;
ListNode node=head.next;
head.next=swapPairs(node.next);
node.next=head;
return node;
}