2014-05-09 26 views
0

我需要编写一个方法来循环查看链表是否在链接列表中。任何帮助?Java搜索LinkedList以获取数据返回true/false?

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 
+3

我不会建议调用类'LinkedList' ..你可能混淆了Java的'LinkedList'类 – Alejandro

+0

你尝试过什么?你创建了LinkedListNode对象吗?为什么不能只看到LinkedListNode.NextNode == null? –

+0

我将遍历的链表将包含数据。我这样做的全部原因是用一组字符(例如“ump”)搜索链接列表,并在列表中出现短语“ump”时返回。 – Cole

回答

0

假设你写的代码为LinkedListNode,你应该知道阉羊与否是Iterable,因此能够通过for-each循环来遍历它。现在,您应该通过使用某种形式的“下一个”指针来递归地或以迭代的方式遍历节点,这些指针在每个节点中都存在,实质上是通过链接进行线性搜索,直到找到您正在查找的数据,或者返回null

下面是关于执行一个链表一些帮助的链接:

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

+0

我确实有一个LinkedList节点类的设置: public class LinkedListNode { \t private Object data; \t private LinkedListNode next; \t \t \t公众一个LinkedListNode(对象数据,一个LinkedListNode下){ \t \t超级(); \t \t this.data = data; \t \t this.next = next; \t} \t \t 公共对象的getData(){ \t \t返回数据; \t} \t public void setData(Object data){ \t \t这个。数据=数据; \t} \t public LinkedListNode getNext(){ \t \t return next; \t} \t public void setNext(LinkedListNode next){ \t \t this.next = next; \t} \t 你推荐这样做的方法是?递归或迭代? 我无法将其作为代码显示,对不起。 – Cole

+0

您可以将该代码作为问题的一部分发布,以便更好地查看它? – Alejandro

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 
} 
+0

该循环将无限运行;) – Alejandro

+0

感谢您指出......忘了移动到下一个节点! – Kakarot

+0

考虑到数据,接下来是私人......我如何使用它而不公开这些属性? – Cole