我正在處理一個賦值的雙端隊列,並且我們遇到了一個問題,即對象引用在通過極端簡單的方法。當通過函數傳遞時節點失去對另一個對象的引用
一些重要的定義:
我們正在編寫class Node {
String s;
Node prev;
Node next;
...
}
class Sentinel extends Node {
Node prev;
Node next;
//Constructor uses that of Node
}
class Deque {
Sentinel start;
...
}
一種方法去除一個deque一個節點,基於給定的字符串。
在雙端隊列:
public void removeSorted(String toRemove) {
// System.out.println(this.start);
// System.out.println(this.start.next);
this.start.next.removeSorted(toRemove);
}
註釋掉的println的顯示正確的哨兵和節點。
然後,在節點:
public void removeSorted(String toRemove) {
if (this.s.equals(toRemove)) {
// System.out.println(this.prev);
// System.out.println(this.prev.next);
this.prev.next = this.next;
this.next.prev = this.prev;
} else if (this.s.compareTo(toRemove) > 0) {
throw new RuntimeException("String does not exist in these nodes!");
} else {
this.next.removeSorted(toRemove);
}
}
中的println爲this.prev
輸出哨兵在第一遞歸,如所預期。但是,this.prev.next輸出null而不是節點。
此功能僅在嘗試刪除第一個節點時直接在Sentinel之後失敗。如果您嘗試刪除任何其他節點,它可以正常工作,並且試圖撥打this.prev.next
將導致非空答案。
爲什麼參考在傳遞給函數時(緊隨其後)消失了,因爲我們在調用函數之前已經指出引用是直接存在的嗎?
爲什麼你有這個'哨兵'呢?爲什麼不僅僅是'節點開始;'當列表爲空時用'start == null'? – hyde 2013-03-18 06:33:25