[英]node delete: terminator node in a singly linked list?
我有一個刪除當前節點的實現。 條件是: 我們只知道當前節點。
這樣做的方式是:
作為以下實現:
public class ListNode<T> {
private ListNode<T> next = null;
private T data;
public ListNode(T data) {
this.data = data;
}
/*
* Add a new node after the current node
* Time Complexity: O(1)
*/
public void add(T data) {
ListNode<T> newNode = new ListNode<T>(data);
newNode.setNext(this.getNext());
this.setNext(newNode);
}
/*
* Delete the current node
* Time Complexity: O(1)
*/
public T delete() {
ListNode<T> nextNode = next;
if (nextNode == null) { /* The current node is the last node. */
return null;
}
T nextData = nextNode.getData();
this.setData(nextData);
this.setNext(nextNode.getNext());
return nextData;
}
/* getters and setters */
}
但是,有一個例外:如果當前節點是列表中的最后一個節點,則該方法將不起作用。
我可以想到一種解決此問題的方法:
TerminatorNode
,它總是在鏈表的末尾。 我想知道:如何執行? 或者,這種節點應該是哪種class
?
編輯1:明確地說,我的問題是:即使鏈表中的最后一個節點,我也能始終刪除該節點? 我想擁有一個TerminalNode
,它始終位於鏈表的末尾,僅代表鏈表的末尾。 (類似於\\0
在字符串的末尾。)然后可以始終使用相同的方法在時間O(1)刪除其他普通節點。
編輯2:這是關於破解編碼面試的一些聲明:
例如,您可以考慮將節點標記為虛擬節點。
這意味着什么?
為了簡單起見,讓我們將終端節點表示為具有data
的LinkedNode
,並將next
為null
。 我們還假設終端節點是結束列表的唯一有效方法。
private boolean isTerminalNode() {
return this.getData() == null && this.getNext() == null;
}
如果列表的末尾始終是終端節點,則可以刪除該終端以外的任何節點。
/*
* Delete the current node Time Complexity: O(1)
*/
public T delete() {
if (this.isTerminalNode()) {
// Cannot delete the terminal node.
// Either throw an IllegalArgumentException or return silently
return null;
}
ListNode<T> nextNode = this.getNext();
this.setData(nextNode.getData());
this.setNext(nextNode.getNext());
return this.getData();
}
但是,現在在節點后添加時可能會遇到類似的問題。
/*
* Add a new node after the current node Time Complexity: O(1)
*/
public void add(T data) {
if (this.isTerminalNode()) {
// Cannot add a node after the terminal node.
// Either throw an IllegalArgumentException, return silently, or add
// the data at the current position and create a new terminal node.
throw new IllegalArgumentException("Cannot add a node after the terminal node");
}
ListNode<T> newNode = new ListNode<T>(data);
newNode.setNext(this.getNext());
this.setNext(newNode);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.