LeetCode 24 JAVA
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode pre = fakeHead;
ListNode ptr = pre.next;
while(ptr != null && ptr.next != null){
ListNode temp = ptr.next;
ListNode next = temp.next;
pre.next = temp;
temp.next = ptr;
ptr.next = next;
pre = ptr;
ptr = next;
}
pre.next = ptr;
return fakeHead.next;
}
}
画图理解。

浙公网安备 33010602011771号