递归实现:(思路非常清晰)
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode second = head.next;
ListNode third = second.next;
second.next = head;
head.next = swapPairs(third);
return second;
}
非递归实现:
假如现在是 1->2->3->4->5->6
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode newHead = head.next;
// a = 1, b = 2
ListNode a=head, b=a.next, pre = null;
while(a!=null && b!=null){
// a.next = 3 ,b.next = 1
a.next = b.next;
b.next = a;
if(pre!=null){
pre.next = b;
}
if(a.next==null) break; // 如果是奇数,下一个为空就会跳出循环,否则就会执行下面三条语句,进行交换
// b = 4, pre = 1, a = 3
b = a.next.next;
pre = a;
a = a.next;
}
return newHead;
}