DEV Community

ramnayan
ramnayan

Posted on

2487. Remove Nodes From Linked List

In this post i'm gone explain liked list an famous leetcode problem that is "Remove Nodes from linked list".

Problem Statement:
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:

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.

Explanation:
In this problem statement state that remove the nodes which have the right side (any place) element greater than. let's understand with given example.

  • Node 13 is the right side of the 5,2 nodes thats why 2,5 should be remove.
  • Node 8 is the right side of 3 node thats why 3 should be remove.

final result would be [13,8]

Solution of the problem:

`/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */

const reverList = function(head){
    let prev = null;
    let curr = head;
    let next = null;

    while(curr!=null){
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }

    return prev;
}

var removeNodes = function(head) {
    // reverse list
    let reversList = reverList(head);

    let maxNode =  reversList;
    let prevNode = reversList;
    let currNode = reversList.next;
    // removed list
    while(currNode != null){
        if(maxNode.val > currNode.val){
            currNode = currNode.next;
        }else{
            maxNode = currNode;
            prevNode.next = currNode;
            prevNode = prevNode.next;
            currNode = currNode.next;
        }
    }

    prevNode.next = null;
    // reverse list
    return reverList(reversList);
};`

Enter fullscreen mode Exit fullscreen mode

If you have any query or suggestions leave your expression๐Ÿ‘จ๐Ÿฟโ€๐Ÿ’ป๐Ÿ™Œ.

Top comments (0)