Skip to content
Advertisement

How to update the nodes in the hash Map in specific key in java?

I want to remove all even nodes from the linked list. How can I update the node in the specific key of the hashmap? H.get(0).next=temp is not working. The desired output is 2 4, but I’m not getting it.

public static void main(String[] args) {
    head = new Node(1);
    head.next = new Node(2);
    head.next.next = new Node(3);
    head.next.next.next = new Node(4);
    head.next.next.next.next = new Node(5);
    Node temp=head;
    HashMap<Integer,Node>H=new HashMap<>();
        while(temp!=null) {
            if(temp.data%2==0) {
                if(!H.containsKey(0)) {
                    H.put(0, temp);
                } else {
                    //This statement is not working
                    H.get(0).next=temp;  
                }
            }
        temp=temp.next;
        }
        head=H.get(0);
        while(temp!=null) {
            System.out.print(temp.data);
            temp=temp.next;
    
        }
    }
}

Advertisement

Answer

  • In the last loop, you wrote while(temp!=null){ but the temp is null after the loop and doesn’t reference the head.
  • I don’t see the value in using HashMap here.

Here’s what we can do to remove all nodes with even data:

Node head;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

Node oddTail = null, curr = head;

while (curr != null) {
    if (curr.data % 2 != 0) { // Odd data
        if(oddTail != null){
            oddTail.next = curr; // Update oddTail
        }

        oddTail = curr;
    }

    curr = curr.next;
}

if(oddTail != null){ // The oddTail.next might point to a node with even data
    oddTail.next = null; 
} else{
    head = null; // No nodes with odd data
}

curr = head;

// Print the list
while(curr != null){
    System.out.println(curr.data);
    curr = curr.next;
}

Output:

1
3
5
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement