
image.png
(图片来源https://leetcode-cn.com/problems/swap-nodes-in-pairs/
)
| 日期 | 是否一次通过 | comment |
|---|---|---|
| 2020-02-17 |
notice:
- 起点竟然是dummy
// cur 是reverse的起点
public ListNode swapPairsN(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curNode = dummy;
while (curNode.next != null && curNode.next.next != null) {
ListNode first = curNode.next;
ListNode second = curNode.next.next;
first.next = second.next;
second.next = first;
curNode.next = second;
curNode = first; // 最容易的错的地方
}
return dummy.next;
}
递归
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;
}