Quantcast
Channel: Coddicted
Viewing all articles
Browse latest Browse all 10

Solved! Leetcode 2487. Remove Nodes From Linked List

$
0
0

Description: Remove Nodes From Linked List

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

<strong>Input:</strong> head = [5,2,13,3,8]
<strong>Output:</strong> [13,8]
<strong>Explanation:</strong> 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

<strong>Input:</strong> head = [1,1,1,1]
<strong>Output:</strong> [1,1,1,1]
<strong>Explanation:</strong> 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

Solution

/**
 * 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 {
    //use stack
    public ListNode removeNodes(ListNode head) {
        ArrayDeque&lt;ListNode&gt; stack = new ArrayDeque&lt;&gt;();
        ListNode p = head;
        while(p!=null){

            //if the stack is not empty or the current node val is greater than the previous node, pop an element from the stack
            while(!stack.isEmpty() &amp;&amp; stack.peek().val &lt; p.val){
                stack.pop();
            }
            stack.push(p);
            p = p.next;
        }

        p = stack.pop();

        //update the next pointer
        while(!stack.isEmpty()){
            ListNode n = stack.pop();
            n.next = p;
            p = n;
        }

        return p;
    }
}

Time Complexity

O(n), where n is the number of nodes in a linkedlist

Space Complexity

O(n), where n is the number of nodes in a linkedlist

Rate this post


Viewing all articles
Browse latest Browse all 10

Trending Articles