我的思路:头插法插两个点,更新头节点,继续插
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode rs = new ListNode();
ListNode curr = rs;
while(head != null && head.next != null) {
ListNode temp = head.next.next;
ListNode temp1 = head.next;
head.next = curr.next;
curr.next = head;
temp1.next = curr.next;
curr.next = temp1;
curr = curr.next.next;
head = temp;
}
if(head != null) curr.next = head;
return rs.next;
}
}
更优美的代码 三指针,直接改变三个指针彼此的方向,不需要头插法
举例:head - 1 - 2 - 3
直接让head指向2,1指向3,2指向1,head指向1
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode rs = new ListNode();
rs.next = head;
for(ListNode p = rs; p.next != null && p.next.next != null; ) {
ListNode a = p.next, b = a.next;
a.next = b.next;
b.next = a;
p.next = b;
p = a;
}
return rs.next;
}
}