[LeetCode] 2487. Remove Nodes From Linked List

CNoodle發表於2024-05-07

You are given the head of a linked list.

Remove every node which has a node with a greater value anywhere to the right side of it.

Return the head of the modified linked list.

Example 1:
Example 1
Input: head = [5,2,13,3,8]
Output: [13,8]
Explanation: The nodes that should be removed are 5, 2 and 3.

  • Node 13 is to the right of node 5.
  • Node 13 is to the right of node 2.
  • Node 8 is to the right of node 3.

Example 2:
Input: head = [1,1,1,1]
Output: [1,1,1,1]
Explanation: Every node has value 1, so no nodes are removed.

Constraints:
The number of the nodes in the given list is in the range [1, 105].
1 <= Node.val <= 105

從連結串列中移除節點。

給你一個連結串列的頭節點 head 。 移除每個右側有一個更大數值的節點。 返回修改後連結串列的頭節點 head 。

思路

根據題意,如果某個 node 的右側有一個比他 val 更大的 node,需要把這個 node 刪除。那麼這裡我們可以反過來思考,如果我們從右往左遍歷整個連結串列,我們可以先把第一個節點的 val 當做最大值,記為 max,再往左遍歷的時候,如果當前節點值比 max 小,則把當前節點移除;否則把當前節點的節點值記為 max,繼續往左遍歷。這樣做的好處是,我們只需要遍歷一次連結串列,就可以把所有需要刪除的節點都刪除掉。不過我們需要將 input 連結串列整個反轉一次,遍歷一次,再反轉回去。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNodes(ListNode head) {
        // corner case
        if (head == null || head.next == null) {
            return head;
        }

        // normal case
        head = reverse(head);
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        int max = 0;
        while (cur.next != null) {
            if (cur.next.val < max) {
                cur.next = cur.next.next;
            } else {
                max = cur.next.val;
                cur = cur.next;
            }
        }
        head = reverse(head);
        return head;
    }

    private ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

相關文章