簡體   English   中英

鏈接列表-刪除排序列表的方法

[英]Linked list - Remove method for Sorted List

在這里的新程序員,我試圖在下面理解和分解以下代碼,以使用remove方法(已排序的鏈表)。 我在下面添加了關於我的理解和不理解的評論。 有人可以闡明一些不清楚的東西嗎?

提前致謝。

/* 1  */ public void remove(E e) throws NotFoundException{
/* 2  */     Node<E> p; //declares node p
/* 3  */     // chunk below determines where to start traversing based on element value. should traverse from head if new element < pos value
/* 4  */     if(pos == head || pos.compareTo(e) >= 0 ){ //I do not understand 2nd equality..why?
/* 5  */         p = head; //traverse list from head
/* 6  */     }else{
/* 7  */         //traverse list from pos
/* 8  */         p = pos;
/* 9  */     }
/* 10 */     for( ;p.next!=null && p.next.compareTo(e)<0; p = p.next); //nothing to initialize?
/* 11 */     //e not found in the list
/* 12 */     if(p.next == null || p.next.compareTo(e) > 0){
/* 13 */         throw new NotFoundException();
/* 14 */     }
/* 15 */     if(p.next == pos){
/* 16 */         //if node to be deleted is pos, update pos to head
/* 17 */         pos = head;
/* 18 */     }
/* 19 */     p.next = p.next.next; //delete node
/* 20 */ }

第4行:這是一個排序列表,因此,如果要刪除的元素大於或等於pos指向的元素,則可以從pos(而不是從列表的開頭)開始移動-(如果您不知道,如果a <b,a.compareTo(b)<0,如果a == b,則a.compareTo(b),如果a <b,則> 0

第10行:在列表中移動,而p.next低於要查找的內容(且不為null)-完成操作后,要么在您要查找的節點上,要么拋出NotFoundException()

還有其他不清楚的地方嗎?

4. if(pos == head || pos.compareTo(e) >= 0 ){ //I do not understand 2nd equality..why? 
5. p = head; //traverse list from head
6. }else{
7. //traverse list from pos 
8. p = pos;  
9. }

首先,這里是compareTo文檔 。第二個相等性檢查pos是否指向“ e”之后的節點。 如果是真的,那么您必須從頭開始遍歷該列表,因為e在pos之前。 否則,e位於pos之后,因此您可以遍歷pos中的列表。 這是因為列表已排序。

10. for( ;p.next!=null && p.next.compareTo(e)<0; p = p.next); //nothing to initialize?
11. //e not found in the list
12. if(p.next == null || p.next.compareTo(e) > 0){
13. throw new NotFoundException();
14. }

在這里,您從選定的位置開始掃描列表,如果到達空節點(列表的末尾)或大於“ e”的節點,則您會知道在其中找不到“ e”列表(因為列表已排序),因此引發了異常

第10行:您不必在這里初始化任何東西,因為您已經在上面初始化了p。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM