Program to remove all Negatives from a Linked-List

In this tutorial, you will get know about likned-list implementation in javascript. Below is a program to remove all the negatives from the linked-list.

Program

class Node { 
    constructor(element) 
    { 
        this.element = element; 
        this.next = null
    } 
} 

class LinkedList { 
    constructor() 
    { 
        this.head = null; 
        this.size = 0; 
    } 
  
    // functions to be implemented 
    addIntoList(element) 
    { 
      // creates a new node 
      var node = new Node(element); 
    
      // to store current node 
      var current; 
    
      // if list is Empty add the 
      // element and make it head 
      if (this.head == null) 
          this.head = node; 
      else { 
          current = this.head; 
    
          // traverse till the end of the list 
          while (current.next) { 
              current = current.next; 
          } 
    
          // add node 
          current.next = node; 
      } 
      this.size++; 
    } 

    removeElement(element) 
    { 
        var current = this.head; 
        var prev = null; 
      
        // iterating the list 
        while (current != null) { 
            // comparison element with  the current element if found then remove the and return true 
            if (current.element == element) { 
                if (prev == null) { 
                    this.head = current.next; 
                } else { 
                    prev.next = current.next; 
                } 
                this.size--; 
                return current.element; 
            } 
            prev = current; 
            current = current.next; 
        } 
        return -1; 
    } 

    printWholeList() 
    { 
        var curr = this.head; 
        var str = ""; 
        while (curr) { 
            console.log(curr.element+"--")
            curr = curr.next; 
        }  
    }
    removeNeagatives() 
    { 
        var curr = this.head; 
        var str = ""; 
        while (curr) { 
            if(curr.element < 0)
              this.removeElement(curr.element)
            curr = curr.next; 
        }  
    } 
} 

let LinkedListObject = new LinkedList();

LinkedListObject.addIntoList(-10)
LinkedListObject.addIntoList(11)
LinkedListObject.addIntoList(-12)

LinkedListObject.removeNeagatives();
LinkedListObject.printWholeList();

Leave a Reply