//递归
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
//迭代
public ListNode swapPairs2(ListNode head) {
ListNode temp = new ListNode(0);
temp.next = head;
ListNode pre = temp;
ListNode first, second;
while (pre.next != null && pre.next.next != null) {
first = pre.next;
second = pre.next.next;
pre.next = second;
first.next = second.next;
second.next = first;
pre = first;
}
return temp.next;
}
网友评论