Check if element of linked list exists
25,700
Solution 1
Just pass the root node and loop through your linkedList:
public boolean member(Node root, Integer val){
Node currentNode = root;//keep track of current node
while(currentNode != null){
//switched currentNode.val and val to avoid null pointer exceptions
if(val.equals(currentNode.val)){
//if you're looking for nulls...still with the original
//if(currentNode.val.equals(val)){
System.out.println("true");
return true;
}
currentNode = currentNode.next();//update current node
}
return false;
}
Solution 2
Ok without recursion:
public boolean member(Integer val){
Node current = node;
while (current != null) {
if (current.val.equals(val)) {
return true;
} else {
current = current.next;
}
}
return false;
}
Solution 3
This solution uses a Boolean function to determine if element exists in linked list.
public boolean doesValExist(int value){
Node traveler = head;
while(traveler != null){
if(traveler.getElement() == value){
return true;
}
traveler = traveler.getNext();
}
return false;
}
Author by
user2779065
Updated on April 13, 2020Comments
-
user2779065 about 4 years
I am trying to determine if the value is a member in the link. if it is a member, it will return true otherwise it returns false. I try to do this
public boolean member(Integer val){ if(node.val.equals(val) || node.next.val.equals(val)){ System.out.println("true"); return true; } return false; }
However, it only check the value of the head and value of the next of the head. What would be other way to check the value of all node?