链表
一定要脑内清晰,指针指向的位置
虚拟头结点
引入 temp
是便于理解,temp
的用途是存储下一个需要 swap 的节点
无需考虑单数情况,因为 while
loop 会把这种情况判掉,因此如果节点数为单数的话,最后一个节点是没有任何改变的。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur, first, second;
cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode temp = cur.next.next.next;
first = cur.next;
second = cur.next.next;
// 关键逻辑:
cur.next = second;
second.next = first;
first.next = temp;
cur = first;
}
return dummy.next;
}
}