簡體   English   中英

刪除任何插入到實現為隊列的 LinkedList 中的對象

[英]Remove any object inserted in a LinkedList implemented as Queue

我有一個實現為隊列的 LinkedList。 remove(object) 方法可以刪除隊列中任意位置的對象,據我所知,這與隊列的先進先出概念相矛盾。 我在這方面理解錯誤。

Queue<Object> q= new LinkedList<>();
//assuming objects have been inserted 
q.remove(a); //this removes the object 'a' present anywhere in the Queue.

出於好奇,我查看了 LinkedList Object 和 Collection 接口中的 remove 方法。 remove 函數的作用是遍歷節點,找到對象,然后解除對象的鏈接。

 public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; }

現在, unlink 方法基本上與節點一起工作,就像隊列一樣,左右迭代以找到該對象。 另外,請記住,這個對象有一個 modCount,它跟蹤修改並實現快速失敗行為(如果出現錯誤)

 E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; }

根本不是一個完整的答案,但是,您可以看到,它遍歷節點。 也許你可以通過書籍和教程來研究 Big O 和算法。 然而,簡單地說,LinkedList 是一種混合包,在這里和那里實現。 所以,FIFO會被保留,並且索引會被跟蹤,但是,除了切割頭或尾節點之外,還會遍歷做刪除。

暫無
暫無

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

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