简体   繁体   中英

Java Searching LinkedList for data return true/false?

I need write a method to loop through a linked list searching to see if Object data is in linked list. Any help?

public class LinkedList {
     private LinkedListNode head;
     public boolean find(Object data){
          for(somethinggoeshere..){
               if(head==data){
                    return true;
          }else{
          return false;
     }
}

Any help?

Edit: My LinkedListNode class:

public class LinkedListNode {

private Object data;
private LinkedListNode next;


public LinkedListNode(Object data, LinkedListNode next) {
    super();
    this.data = data;
    this.next = next;
}

public Object getData() {
    return data;
}
public void setData(Object data) {
    this.data = data;
}
public LinkedListNode getNext() {
    return next;
}
public void setNext(LinkedListNode next) {
    this.next = next;
}
}

Edit: Final solution for those who are interested:

public class LinkedList {

private LinkedListNode head;

public boolean find(Object data){
      LinkedListNode temp = head;
      while(temp!= null)  // check if you have reached the tail
      {
           if(data.equals(temp.getData()))
           {
                return true;
           }
           temp = temp.getNext(); // move to the next node
      } // end of while loop
      return false;
 } // end of find method

Assuming that you wrote the code for LinkedListNode , you should know wether or not is Iterable , and thus be able to loop through it with a for-each loop like that.

As it stands, you should traverse the nodes either recursively or in an iterative manner, by using some form of "next" pointers that is held within each node, and in essence do a linear search through the links until you find the data you are looking for, or return null .

Here's a link for some help on implementing a linked list:

http://www.danielacton.com/Data-Structures/Linked-List/Java/

You need to loop through your LinkedList and search for the data. If you reach tail of the list and still unable to find the data this implies that data is not in the LinkedList.

I am assuming that LinkedListNode has a member variable data to store the data in each node. Below is the corrected code :

 public class LinkedList {

 private LinkedListNode head;

 public boolean find(Object data)
 {
      LinkedListNode temp = head;
      while(temp!= null)  // check if you have reached the tail
      {
           if(data.equals(temp.getData()))
           {
                return true;
           }
           temp = temp.getNext(); // move to the next node
      } // end of while loop
      return false;
  } // end of find method
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM