【Leetcode】86. 分隔鏈表

雙十一這波熬了兩個通宵,有點傷,又開始A題,總結技術了。

題目

給定一個鏈表和一個特定值 x,對鏈表進行分隔,使得所有小於 x 的節點都在大於或等於 x 的節點之前。

你應當保留兩個分區中每個節點的初始相對位置。

示例:

輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5

題解

鏈表的題目基本都是分三步走: 1.連過來。把想要的節點連到你需要的鏈表上 2.指針走。該節點處理完了,在原來的鏈表上要走一步. 3.斷後路。當前鏈表不要和原來鏈表有連接 4.調狀態。調整當前各指針的記錄狀態

其他部分僅僅是爲了保存狀態的。

鏈表的題目刷過100道之後我會做一個彙總,鏈表題目基本就是最簡單的這三步,面到就是賺到。

java

    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode preDummy = new ListNode(-1);
        ListNode dummy = new ListNode(-1);
        preDummy.next = dummy;
        ListNode res = preDummy;
        ListNode tail = dummy;

        while (head != null) {
            ListNode current = head;
            if (head.val < x) {
                //連過來
                preDummy.next = current;
                //指針走
                head = head.next;
                //斷後路
                current.next = dummy;
                preDummy = preDummy.next;
            } else {
                //連過來
                tail.next = current;
                //指針走
                head = head.next;
                //斷後路
                current.next = null;
                tail = tail.next;
            }
        }
        preDummy.next = dummy.next;
        return res.next;
    }

python

class Solution:
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        preDummy = ListNode(-1)
        dummy = ListNode(-1)
        preDummy.next = dummy
        res = preDummy
        tail = dummy

        while head is not None:
            current = head
            if head.val < x:
                # 連過來
                preDummy.next = current
                # 指針走
                head = head.next
                # 斷後路
                current.next = dummy
                # 調狀態
                preDummy = preDummy.next
            else:
                # 連過來
                tail.next = current
                # 指針走
                head = head.next
                # 斷後路
                current.next = None
                # 調狀態
                tail = tail.next
        preDummy.next = dummy.next
        return res.next

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章