public class Node {
public String name;
public Node next;
public Node(String name, Node next ){
this.name = name;
this.next = next;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public Node getNext(){
return next;
}
public void setNext(Node n){
next = n;
}
public String toString() {
return "Name " + name;
}
}
public class LinkedList {
Node head = null;
int nodeCount= 0;
int counter = 0;
LinkedList(){
head = null;
}
public boolean isEmpty(){
return (head != null);
}
public void insertNode( String name ){
if( head == null){
head = new Node(name, null);
nodeCount++;
}else{
Node temp = new Node(name, null);
temp.next = head;
head = temp;
nodeCount++;
}
}
public Node reverseTest(Node L){
if(L == null || L.next ==null){
return L;
}
Node remainingNode = reverseTest(L.next);
Node cur = remainingNode;
while(cur.next !=null){
cur=cur.next;
}
L.next = null;
cur.next = L;
return remainingNode;
}
public boolean searchLinkedList(Node L, String S){
if (L == null)
return false;
else{
while(L !=null){
if(S.equals(L.name))
return true;
L= L.next;
}
}
return false;
}
public String toString(){
Node current = head;
String output = "";
while(current !=null){
output += "[" + current.getName() + "]";
current = current.getNext();
}
return output;
}
}
public class LinkedListDemo {
public static void main(String[] args){
LinkedList FriendList = new LinkedList();
FriendList.insertNode("First");
FriendList.insertNode("Second");
FriendList.insertNode("Third");
FriendList.insertNode("Fourth");
FriendList.searchLinkedList(FriendList.head, "Hello");
String NameList = FriendList.toString();
System.out.println(NameList);
System.out.println("Finish");
}
}
I have a singly linked list. I wanted to search for a value that is not present in the linkedlist and in the last loop when it reaches L = L.next I receive NPE. I don't see what is the mistake here. Please point to the right direction.
As I pointed out in the comments, there is no errors. Your IDE is just showing you its last reading of these properties.
When you get to the last loop here:
L is indeed equal to null; which means that when your IDE tries to read its properties (name and next), it (and only IT, not your program's actual output) gets a reasonable NullPointerException.
The program otherwise runs fine.