Below is a simple implementation of a linked list. I have just added the relevant code. First, I add some values to the list, 10,990 and 10000. When I am searching for the same values, I get true for key = 10, but false for key = 990 and key = 10000, though it should be true. Also, if I change the second value from 990 to 99 and search for key = 99, this time I am getting a true.
I am not sure about using generic type. I guess I am doing something wrong there. Because if I replace generic type with int, I get the correct behavior. Please suggest.
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<Integer> num = new LinkedList<Integer>();
num.add(10);
num.add(990);
num.add(10000);
int key = 10;
System.out.println("Key " + key + " found ?" + num.findValue(key));
key = 990; //also checked for Integer key = 990
System.out.println("Key " + key + " found ?" + num.findValue(key));
key = 10000;
System.out.println("Key " + key + " found ?" + num.findValue(key));
}
}
class LinkedList<T>{
private Node<T> first;
private class Node<T>{
private T data;
private Node<T> next;
public Node(T data){
this.data = data;
this.next = next;
}
}
public void add(T data){
Node<T> nn = new Node<T>(data);
nn.next = first;
first = nn;
}
public boolean findValue(T key){
Node current = first;
while(current != null){
if(current.data == key)
return true;
else
current = current.next;
}
return false;
}
}