[英]Linked list find() method . How to
好的,我有一個鏈表(不是集合),並且創建了一個新方法來在鏈表中查找對象。 所以像這樣:
public Object find(Linked obj) {
Linked newObj = firstLink;
while(newObj != null) {
if(newObj == obj) {
return obj;
}
else {
newObj = newObj.next;
}
}
順便說一下,我有2個類 : Linked
和Linkedlist
。 在第一個中,我參考了下一個節點和顯示功能。 主要動作是在Linkedlist中,這里有所有方法,例如insert,display和firstLink
引用(列表中最后插入的節點)(我的find()方法也在此類中)。 因此,在我的主要職能中,我正在這樣做:
Linkedlist obj = new Linkedlist();
obj.insert("Auto");
Linkedlist obj2 = new Linkedlist();
obj2.insert("Moto");
以及如何調用我的方法find()
來檢查我的Linkedlist
是否具有(例如) obj2
?
這樣想:
您具有Linked類(這是一個鏈接列表節點,每個節點應具有下一個指針和該節點內的元素)。 因此,此類應具有構造函數,setter和getter方法。
另一方面,Linkedlist類是您管理Linked對象(即管理鏈表節點)的主類。 在此類中,您應該引用根節點(您插入的第一個節點)。 因此,在您的程序中,您應該只將一個/多個Linked對象和Linkedlist作為主類。
Linked root = new Linked("Auto",null); //here Linked constructor takes 2 parameters, the element and the next pointer.
//Since you only inserted one element so far, the next element should be null.
//Insert another element
insertAtEnd("Moto");
public void insertAtEnd(String element){
Linked curr = root;
while(curr.next != null) curr = curr.next;
curr.setNext(new Linked(element,null);
}
public Linked findElement(String element){
Linked curr = root;
while(curr!=null){
if(curr.getElement().equals(element)) return curr;
else curr = curr.next;
}
return null; //element not found
}
要將LinkedList中的單個對象與另一個對象進行比較:
實現Linked
equals()
方法。 在此方法內,檢查兩個對象(迭代中的當前對象和要查找的對象)中包含的字符串是否相同。 這樣做,您應該使用String.equals(String other)
方法
要比較兩個LinkedList,請編寫另一個equals()
方法。 這次是LinkedList
。 在這種方法中,您應該比較兩個清單中元素的數量。 如果列表包含相同數量的元素,則可以使用先前定義的Linked.equals()
比較列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.