简介
设置多个指针.
code
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null) return null;
ListNode newHead = new ListNode(-1, null);
newHead.next = head;
ListNode newTail = new ListNode(-1, null);
ListNode p1 = newHead;
ListNode p2 = head;
ListNode p3 = head.next;
ListNode p4 = null;
while(p3 != null){
p4 = p3.next;
p1.next = p3;
p2.next = p4;
p3.next = p2;
if(p4 == null) return newHead.next;
p4 = p2;
p2 = p3;
p3 = p4;
p1 = p1.next.next;
p2 = p2.next.next;
p3 = p3.next.next;
}
return newHead.next;
}
}
但是我觉得递归更合适
code
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》