143. Reorder List - LeetCode

Question

143. Reorder Listjava

Solution

題目大意:給一個鏈表,將這個列表分紅先後兩部分,後半部分反轉,再將這兩分鏈表的節點交替鏈接成一個新的鏈表code

思路 :先將鏈表分紅先後兩部分,將後部分鏈表反轉,再將兩部分鏈表鏈接成一個新鏈表ip

鏈表取中間節點思路:龜兔賽跑,每秒鐘烏龜跑1步,兔子跑2步,當兔子跑徹底程時烏龜正好跑完一半leetcode

鏈表反轉實現思路 :get

Java實現:it

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        
        ListNode mid = findMid(head);
        ListNode l2 = mid.next;
        mid.next = null; // 將前半部分鏈表截斷
        l2 = reverse(l2); // 將後半部分鏈表反轉
        ListNode l1 = head;
        // 組裝新的鏈表
        while (l1 != null && l2 != null) {
            ListNode tmp = l1.next;
            l1.next = l2;
            l2 = l2.next;
            l1.next.next = tmp;
            l1 = tmp;
        }
    }
    
    // 返回鏈表的中間節點
    // 龜兔賽跑,每秒鐘烏龜跑1步,兔子跑2步,當兔子跑徹底程時烏龜正好跑完一半
    ListNode findMid(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    
    // 返回反轉後的鏈表
    ListNode reverse(ListNode head) {
        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }
}
相關文章
相關標籤/搜索