水题啊,不想说啥。分析题意,可发现两个节点切换时,需要改动的除了两个节点,还有两个节点的前一个节点。代码中middle与back,代表将要交换的两个节点。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p = new ListNode(Integer.MAX_VALUE);
ListNode ans = p;
p.next = head;
while (p != null) {
ListNode front = p;
ListNode middle = p.next;
if (middle == null) break;
ListNode back = p.next.next;
if (back == null) break;
swap(front, middle, back);
p = p.next;
p = p.next;
}
return ans.next;
}
private void swap(ListNode front, ListNode middle, ListNode back) {
front.next = back;
middle.next = back.next;
back.next = middle;
}
}