1. 程式人生 > >[LeetCode]143. Reorder List

[LeetCode]143. Reorder List

leet bsp pos fas fast log order 一個 合並

這個題是基本技能的一個集合,用到了快慢指針找中點,反轉鏈表和合並鏈表

一些鏈表的拼接過程要熟練

public void reorderList(ListNode head) {
        /*
        先找到中點,然後反轉後部分,然後組合鏈表
         */
        if (head==null) return;
        //第一步,快慢指針找中點
        ListNode slow = head;
        ListNode fast = head;
        while (fast!=null&&fast.next!=null
) { slow = slow.next; fast = fast.next.next; } ListNode back = slow.next; slow.next = null; //反轉後邊 ListNode pre = null; while (back!=null) { ListNode next = back.next; back.next = pre; pre
= back; back = next; } ListNode res = head; //拼接 while (res!=null&&pre!=null) { ListNode t1 = res.next; ListNode t2 = pre.next; res.next = pre; pre.next = t1; pre
= t2; res = t1; } }

[LeetCode]143. Reorder List