Comparator in Linked Lists - java

I'm writing a program that is a linked list, trying to insert something in order and I've used this in my code but it keeps saying that it's a NullPointerException, and I'm not sure why.
public SortedLinkedList<T> add(T element) {
Node insert = new Node(element);
Then I check to make sure curr isn't null.
if (comparator.compare(curr.data, insert.data) <= 0
&& comparator.compare(curr.next.data, insert.data) > 0){

Then I check to make sure curr isn't null.
The code you've posted isn't checking to see if curr is null, it is doing a comparison, and probably trying to do a comparison on an Object that does not exist.
You should check to make sure that the next element (curr.next) in your linked list exists before you try to access it.

I dont't know what's the body of comparator.compare, but it there's no null check in that method, you should do something like this.
if (curr != null && curr.data!=null && comparator.compare(curr.data, insert.data) <= 0
&& comparator.compare(curr.next.data, insert.data) > 0){

Related

Remove duplicate elements from a linked list

I was trying to read a program of removing duplicate elements in a linked list. I am confused about the break conditions put in the while loop. Below is the code.
public static <T> void removeDuplicates(SinglyLinkedList<T> list) {
SinglyLinkedList<T>.Node current = list.headNode; // will be used for outer loop
SinglyLinkedList<T>.Node compare = null; // will be used for inner loop
while ( current != null && current.nextNode != null) {
compare = current;
while (compare.nextNode != null) {
if (current.data.equals(compare.nextNode.data)) { //check if duplicate
compare.nextNode = compare.nextNode.nextNode;
} else {
compare = compare.nextNode;
}
}
current = current.nextNode;
}
}
The statement while ( current != null && current.nextNode != null) is confusing to me. If I remove current != null from the statement the output is produced same. Suppose the list is 1 -> 2 -> 3 -> null. Now initially current is at 1 , then if we traverse the list and when current points to 3 , at that moment (current.nextNode == null) and if I use only while( current.nextNode != null , that does the job for me. Then why the author has used current != null. Please help me clear the confusion.
A completely empty list would have current be null. The dot is the dereference operator - dereferencing null causes a NullPointerException. Hence, calling that method with an empty list would cause an NPE whereas the correct action is to do nothing ('remove all duplicates from this empty list' is a job that can be done, and it is done by doing nothing - there are no duplicates in an empty list, thus, nothing to remove).
For a non-empty list, indeed, that part of the while clause is never going to be relevant. Given that it would never get there (the last node in the list would already fail the while clause due to having a current.nextNode of null).

How check if a node exists in Java using conditional operator?

Node curr;
if(curr) sop(curr.data)
This is throwing an error that Node cannot be converted to boolean. Can anyone please suggest a way to check if the node exist or not?
Can you try it as:
Node curr;
if(curr != null) {
sop(curr.data)
}
The reason is unlike C++, we can not use objects as booleans in case they are null.

NullPointerException in a while loop using a Binary Tree node

I am using a binary tree structure here. I am getting a "NullPointerException" from the line containing the while statement. I am completely confused about why that would be.
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
// Move up the Binary Tree to create code.
while(currNode.getParent() != null) {
// The loop does some stuff that doesn't
// affect what is assigned to currNode.
// Move to the parent node for the next iteration.
currNode = currNode.getParent();
} // End the while loop.
return code; // Return the string of binary code.
Find value is a method from my BinaryTree class that searches for and finds the node containing specific data. I know this works from testing it separately outside of this implementation.
The only reason why the while-loop statement can throw a NPE is, when currNode is null. I suspect findValue() returned null.
I guess one fix (when you care about the topmost node) would be:
while(currentNode != null) {
rootNode = currentNode;
currentNode = currentNode.getParent();
}
Or the typical pattern which relies on boolean shortcut evaluation:
while(curentNode != null && currentNode.getParent() != null)
Or my prefered solution using guards:
if (currentNode == null)
throw NotFound(); // or return something
while(curentNode.getParent() != null) {
If you see the code:
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
I guess, currNode is getting some value if findValue() able to search data else it is returning NULL values.
When it returns a NULL value it will throw NPE.
To avoid it, you can modify your code a little bit.
while(currNode != null && currNode.getParent != null) {
// your code here
}

Setting myself to null - Java

I came across the following problem:
Delete a node in the middle of a singly linked list, given only access to that node. (head is not given)
Now there are a lot of solutions and they all do not work when the element to be deleted is the last node.
Why wouldn't this work?
public static void removeNode (Node n){
if(n.next == null){ //n is the last node
n= null;
return;
}
//handling general case here
}
Java passes parameters by value, so setting n to null has no effect outside of the method. This means the method essentially does nothing when passed the last node of a list.
You need to set null the reference in the previous node, not the variable that references to your last node, something like this:
if(n.next == null) {
prev.next = null;
return;
}
n is local to the method, so changing its value won't affect the list itself. You need to modify the next of the previous node, which you do not have access to.

Searching for a node in a tree in Java

I have a binary tree made with the following constructor:
public Person(String name, int age, char gender, Person c1, Person c2)
where c1 is the left child and c2 is the right child.
I want to write a method that searches for a particular name within a maximum generation. So like a.depthFirstSearch(Eva, 1); where Eva is the name to search for and 1 is the maximum number of generations (or levels) I can look into.
Here's what I have:
EDIT:
public Person depthFirstSearch(String name, int maxGeneration)
{
{
Person temp;
if (maxGeneration>1){
if (this.name.equals(name)){
temp=this;
return temp;
}
else{
if (child1!=null)
temp=child1.depthFirstSearch(name, maxGeneration-1);
if (child2!=null)
temp=child1.depthFirstSearch(name, maxGeneration-1);
}
}
return null;
}
}
There's two problems here. I think depth gets reset to 0 every time the function calls itself, so I know I can either keep track of depth somewhere else or find an alternative. The other problem, I think, is that child2 is never really reached, since I return at child1. I'm not really sure how this works so if someone could explain that, that'd be great. Any suggestions for some fixes?
Also, I'm told that I have to search depth first, meaning looking into the deeper generations first. I'm not really sure what that means and how different it is from the logic I'm using in my implementation.
Since you decrement maxGeneration in each recursive call, you don't need the depth variable at all: when maxGeneration == 0 you simply don't search any more and return null.
As for your other problem, instead of directly returning the value of child1.depthFirstSearch(...), store the value in a temporary variable. If it is not null, you have found the node, so return it immediately, otherwise continue searching under child2.
Update:
It should be if (maxGeneration >= 1) ... (greater than or equal to), otherwise the last call with maxGeneration == 1 will always return null. Alternatively, you can just check for 0 and return null:
if (maxGeneration == 0)
return null;
// rest of your code
Also, you still aren't using the return value to check if the node was actually found in the left subtree or not. Right now, even if you find the node under child1, you still look under child2 and you will end up returning null, which is wrong. You need to search under child2 only if the left search returned null:
Person temp;
if (child1 != null) {
temp = child1.depthFirstSearch(name, maxGeneration-1);
if (temp != null)
return temp; // found the node, just return
}
// otherwise the following code will execute
if (child2 != null) {
temp = child2.depthFirstSearch(name, maxGeneration-1);
if (temp != null)
return temp; // found the node, just return
}
// didn't find node under either child
return null;

Categories