
迭代法
java
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode result = new ListNode(0);
result.next=head;
ListNode curr = result;
while(curr.next !=null && curr.next.next!=null){
ListNode next = head.next;
ListNode tmp = next.next;
curr.next=next;
next.next=head;
head.next=tmp;
curr=head;
head=head.next;
}
return result.next;
}
递归法
java
public ListNode swapPairs(ListNode head) {
if(head == null || head.next==null){
return head;
}
ListNode next = head.next;
head.next = swapPairs(head.next.next);
next.next=head;
return next;
}