
方法一:迭代
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode pre = dummy, cur = head;
while (cur != null && cur.next != null) {
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = cur;
pre.next = tmp;
pre = cur;
cur = pre.next;
}
return dummy.next;
}
}
方法二:递归
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tmp = head.next;
head.next = swapPairs(tmp.next);
tmp.next = head;
return tmp;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tmp = head.next.next;
ListNode res = head.next;
head.next.next = head;
head.next = swapPairs(tmp);
return res;
}
}