24. [M] Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/
初始 : (p) (1/c1) -> (2/c2) -> (3/n) -> (4)
更新 c1 -> n : (p) (1/c1) -> (3/n) -> (4)
更新 c2 -> c1 : (p) (2/c2) -> (1/c1) -> (3/n) -> (4)
更新 p -> c2 : (p) -> (2/c2) -> (1/c1) -> (3/n) -> (4)
更新 p, c1 : (2) -> (1/p) -> (3/c1) -> (4/c2) class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// (p) (1/c1) -> (2/c2) -> (3/n) -> (4)
ListNode p = null, c1 = head, c2 = null, n = null;
head = c1.next;
while (c1 != null && c1.next != null) {
c2 = c1.next;
n = c2.next;
c1.next = n;
c2.next = c1;
if (p != null) {
p.next = c2;
}
p = c1;
c1 = n;
}
return head;
}
}最后更新于