我需要編寫一個方法來循環查看鏈表是否在鏈接列表中。任何幫助?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
我不會建議調用類'LinkedList' ..你可能混淆了Java的'LinkedList'類 – Alejandro
你嘗試過什麼?你創建了LinkedListNode對象嗎?爲什麼不能只看到LinkedListNode.NextNode == null? –
我將遍歷的鏈表將包含數據。我這樣做的全部原因是用一組字符(例如「ump」)搜索鏈接列表,並在列表中出現短語「ump」時返回。 – Cole