2

I have a list of x numbers that I need to evaluate which are higher than 50 and delete those from the list and then print out the new list. I can't figure out how to add the condition >50 because it renders a blank array. Also, is there a more time efficient way to write this? Appreciate all the help. I'm very confused.

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

class LinkedList {
  constructor(head = null) {
    this.head = head
  }
}

let firstNode = new Node(38);
let list = new LinkedList(firstNode);

let secondNode = new Node(74);
firstNode.next = secondNode;

let thirdNode = new Node(87);
secondNode.next = thirdNode;

let fourthNode = new Node(21);
thirdNode.next = fourthNode;

let fithNode = new Node(91);
fourthNode.next = fithNode;

let sixthNode = new Node(98);
fithNode.next = sixthNode;

let seventhNode = new Node(73);
sixthNode.next = seventhNode;

let eigthNode = new Node(41);
seventhNode.next = eigthNode;

let nithNode = new Node(29);
eigthNode.next = nithNode;

let tenthNode = new Node(3);
nithNode.next = tenthNode

let eleventhNode = new Node(72);
tenthNode.next = eleventhNode;

let twelthNode = new Node(94);
eleventhNode.next = twelthNode;

let thirteenthNode = new Node(12);
twelthNode.next = thirteenthNode;

let fourteenthNode = new Node(13);
thirteenthNode.next = fourteenthNode;

let fiftheenthNode = new Node(16);
fourteenthNode.next = fiftheenthNode;

let currentNode = list.head;

while (currentNode != null && currentNode > 50) {
  console.log(currentNode.data);
  currentNode = currentNode.next;
}

3
  • I don't see a condition at all. What have you tried in your while loop that didn't work? In what way did it not work? Commented Oct 26, 2022 at 1:32
  • @HunterMcMillen I added the code I had tried before. It does not display anything at all. Commented Oct 26, 2022 at 1:36
  • You are stopping your loop when you encounter any element <= 50. Your first node is 38 which is <= 50 so your while loop does not execute. Commented Oct 26, 2022 at 1:47

4 Answers 4

2

You need to make exceptions for the head, and the loop you're using should actually be used for deleting inside another loop that goes through all the nodes (so the outer loop cannot filter by currentNode.data > 50).

I've edited your code so that it should behave more as you were asking for:

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

    class LinkedList {
        constructor(head = null) {
            this.head = head
        }

        //for printing
        printable(sll) {
            if (this.head == null) {
                return 'Empty list';
            }
            let sll_str = `${this.head.data}`;
            let cNode = this.head.next;
            while (cNode != null) {
                sll_str += `, ${cNode.data}`;
                cNode = cNode.next;
            }
            return sll_str;
        }
    }


    let firstNode = new Node(38);
    let list = new LinkedList(firstNode);

    let secondNode = new Node(74);
    firstNode.next = secondNode;

    let thirdNode = new Node(87);
    secondNode.next = thirdNode;

    let fourthNode = new Node(21);
    thirdNode.next = fourthNode;

    let fithNode = new Node(91);
    fourthNode.next = fithNode;

    let sixthNode = new Node(98);
    fithNode.next = sixthNode;

    let seventhNode = new Node(73);
    sixthNode.next = seventhNode;

    let eigthNode = new Node(41);
    seventhNode.next = eigthNode;

    let nithNode = new Node(29);
    eigthNode.next = nithNode;

    let tenthNode = new Node(3);
    nithNode.next = tenthNode

    let eleventhNode = new Node(72);
    tenthNode.next = eleventhNode;

    let twelthNode = new Node(94);
    eleventhNode.next = twelthNode;

    let thirteenthNode = new Node(12);
    twelthNode.next = thirteenthNode;

    let fourteenthNode = new Node(13);
    thirteenthNode.next = fourteenthNode;

    let fiftheenthNode = new Node(16);
    fourteenthNode.next = fiftheenthNode;

    let currentNode = list.head;

    console.log("old list: ", list.printable());
    while (currentNode != null) {
        if (list.head == currentNode && currentNode.data > 50) {
            list.head = currentNode.next;
            console.log("deleting ", currentNode.data);
            let toDel = currentNode;
            delete (toDel);
        } else {
            console.log(currentNode.data);
            let newNext = currentNode.next;
            while (newNext != null && newNext.data > 50) {
                let toDel = newNext;
                newNext = newNext.next;
                console.log("deleting ", toDel.data);
                delete(toDel);
            }
            currentNode.next = newNext;
        }
        currentNode = currentNode.next;
    }
    console.log("\nnew list: ", list.printable());

(I also added a function to the LinkedList class to make it easier to print.)

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much!!! It works as intended now. I really appreciate your help!!!
@AquilesBailo actually, I'm really sorry, but I forgot a crucial part - linking the previous to the next acceptable node after skipping the deleted ones [I'm new to this too 😅]. I've edited to correct that, and also added a print function to the LinkedList class so you can clearly check what the lists look like before and after
2

This can be done with looping on the created Linkedlist and if the value is less than equal 50 than put it into new linkedlist and map it. The last console is to print out the actual linkedlist, because intially we created dummyHead with Infinity value so our result starts from the next of resultHead.

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

class LinkedList {
  constructor(head = null) {
    this.head = head
  }
}

let firstNode = new Node(38);
let list = new LinkedList(firstNode);

let secondNode = new Node(74);
firstNode.next = secondNode;

let thirdNode = new Node(87);
secondNode.next = thirdNode;

let fourthNode = new Node(21);
thirdNode.next = fourthNode;

let fithNode = new Node(91);
fourthNode.next = fithNode;

let sixthNode = new Node(98);
fithNode.next = sixthNode;

let seventhNode = new Node(73);
sixthNode.next = seventhNode;

let eigthNode = new Node(41);
seventhNode.next = eigthNode;

let nithNode = new Node(29);
eigthNode.next = nithNode;

let tenthNode = new Node(3);
nithNode.next = tenthNode

let eleventhNode = new Node(72);
tenthNode.next = eleventhNode;

let twelthNode = new Node(94);
eleventhNode.next = twelthNode;

let thirteenthNode = new Node(12);
twelthNode.next = thirteenthNode;

let fourteenthNode = new Node(13);
thirteenthNode.next = fourteenthNode;

let fiftheenthNode = new Node(16);
fourteenthNode.next = fiftheenthNode;

let currentNode = list.head;
let resultNode = new Node(-Infinity);
let resultHead = resultNode;
while (currentNode != null) {
  //console.log(currentNode.data);
  if(currentNode.data <= 50){
    resultNode.next = new Node(currentNode.data);
    resultNode = resultNode.next;
  }
  currentNode = currentNode.next;     
}
console.log(resultHead.next);

2 Comments

thank you so much!! I got the results I was looking for, in the console it displays next: Node { data: 38, next: Node { data: 21, next: [Node] } }... how can I access the contents of the node? I need to display the list as 38, 21, 41, 29 etc... Thank you once again!!!
If your problem says return head then this will work and if problem says returning array then you need to create resultArr and have to use push method if condition meets. You can remove resultNode, resultHead. At the end, you can direcy print it or loop through and do console.
1

I am happy that you choose Javascript for LinkedList like me. I will provide you with the Solution, please refer to this :

function deleteNode(position)
{
     
    // If linked list is empty
    if (head == null)
        return;
     
    // Store head node
    var temp = head;
     
    // If head needs to be removed
    if (position == 0)
    {
         
        // Change head
        head = temp.next;
        return;
    }
     
    // Find previous node of the node to be deleted
    for(i = 0; temp != null && i < position - 1; i++)
        temp = temp.next;
     
    // If position is more than number of nodes
    if (temp == null || temp.next == null)
    return;
     
    // Node temp->next is the node to be deleted
    // Store pointer to the next of node to be deleted
    var next = temp.next.next;
     
    // Unlink the deleted node from the list
    temp.next = next;
}

Here you can pass position = position of the linked list element you want to delete.

Just implement the below code firstly with paper and pen after that you will understand this.

For any confusion, please let me know by commenting here.

Happy Coding !!

1 Comment

thanks for your detailed answer! I still get the same result, the condition of > 50 is not applied. I need to use the traverse and then delete the data. Any hints with that?
1

Another solution would be to keep track of the previous node. This allows to efficiently skip nodes:

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

class LinkedList {
  constructor(head = null) {
    this.head = head
  }
  
  static fromArray(numbers) {
    if (numbers.length === 0) { 
      return null; 
    }
  
    const [first, ...rest] = numbers;
    const head = new Node(first);

    let current = head;
    rest.forEach(n => {
      const newNode = new Node(n);
      current.next = newNode;
      current = newNode;
    });

    return new LinkedList(head); 
  }
  
  toString() {
    let current = this.head;
    let repr = "";
    while (current != null) {
      repr += current.data + ' -> '
      current = current.next;
    }
    
    repr += 'null';
    return repr;
  }
}

let list = LinkedList.fromArray(
  [38, 74, 87, 21, 91, 98, 73, 41, 29, 3, 72, 94, 12, 13, 16]
);

console.log("BEFORE: ", list.toString());

let current = list.head;
let previous = null;
while (current != null) {  
  if (current.data <= 50) {
    // value is in the valid range, update pointers
    previous = current;
    current = current.next;
    
    // skip to next loop iteration
    continue;
  } 
  
  if (current === list.head) {
    // if we are at the head of the list there is no previous value
    // overwrite the head
    list.head = current.next;
  }
  else {
    // if we are past the head of the list there is a previous value
    // skip the current value by updating the previous node's 'next' to the
    // current node's next
    previous.next = current.next; 
  }
  
  // advance to the next element
  current = current.next;
}

console.log("AFTER: ", list.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.