leetcode -- Swap Nodes in Pairs
双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
加一个safeGuard可以避开链表长度为2的检测。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode swapPairs(ListNode head) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 17 if(head == null) 18 return null; 19 20 ListNode safeG = new ListNode(-1); 21 safeG.next = head; 22 ListNode before = safeG; 23 ListNode cur = safeG.next; 24 ListNode after = cur.next; 25 26 while(after != null){ 27 ListNode tmp = after.next; 28 after.next = cur; 29 cur.next = tmp; 30 before.next = after; 31 before = cur; 32 if(before.next == null) 33 break; 34 35 cur = before.next; 36 after = cur.next; 37 } 38 39 head = safeG.next; 40 return head; 41 42 } 43 }