1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = null; ListNode init = null; ListNode res = init; ListNode cur = head; ListNode temp = null; while (cur != null){ if (cur.next == null){ if (init.next == null){ init.next = cur; }else if(init.next.next == null){ init.next.next = cur; } break; } temp = cur.next.next; cur.next.next = null; if (init == null){ pre = cur.next; cur.next = null; pre.next = cur; init = pre; res = init; init = init.next; }else{ pre = cur.next; cur.next = null; pre.next = cur; if (init.next == null){ init.next = pre; init = init.next; }else if(init.next.next == null){ init.next.next = pre; init = init.next.next; } } cur = temp; pre = pre.next.next; } return res; }
|