Java搜索LinkedList的数据返回true / false?

时间:2014-05-09 20:12:33

标签: java for-loop linked-list

我需要编写一个循环遍历链表的方法,以查看对象数据是否在链表中。有什么帮助吗?

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

任何帮助?

编辑:我的LinkedListNode类:

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;
}
}

编辑:感兴趣的人的最终解决方案:

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

2 个答案:

答案 0 :(得分:0)

假设您编写了LinkedListNode的代码,您应该知道是否Iterable,因此可以使用for-each循环遍历它。

就目前而言,您应该通过递归或迭代方式遍历节点,方法是使用每个节点中保存的某种形式的“下一个”指针,实质上是通过链接进行线性搜索,直到找到您要查找的数据,或返回null

以下是有关实施链接列表的一些帮助的链接:

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

答案 1 :(得分:0)

您需要遍历LinkedList并搜索数据。如果到达列表尾部但仍无法找到数据,则表示数据不在LinkedList中。

我假设LinkedListNode有一个成员变量数据来存储每个节点中的数据。以下是更正后的代码:

 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
}