[英]Delete a node from Singly Linked list at any index using a single method/function in java
我想從 java 的單鏈表中創建和刪除一個節點。 刪除方法將獲取節點的索引並刪除該節點。
邏輯正常,但它沒有刪除第一個索引(0)處的節點我如何修改此代碼以便它可以刪除任何 position 處的節點,而無需使用額外的循環。 我知道我在代碼中使用起始索引為 1,但我無法理解如果輸入的索引為零,那么程序如何使用相同的循環刪除“previousNode”。 它將需要另一個循環(基於此邏輯)。 有沒有辦法刪除這個額外的循環
public E deleteNode(int t) throws IndexOutOfBoundsException{
if(size==0)
return null;
if(t>=size)
throw new IndexOutOfBoundsException("Invalid Input");
Node<E> previousNode=head;
Node<E> currentNode=previousNode.getNext();
int currentIndex=1;
while(currentIndex<t){
previousNode=previousNode.getNext();
currentNode=previousNode.getNext();
currentIndex++;
}
previousNode.setNext(currentNode.getNext());
size--;
return currentNode.getElement();
}
如果用戶輸入索引 0,那么 {1,2,3,4} 的 output 應該是 {2,3,4} 但我得到 {1,3,4}。
一種選擇是將其作為特殊情況處理,因為它需要更新head
。
if (t == 0) {
head = head.getNext();
}
//rest of your code..
Node<E> previousNode=head;
//...
或者,你可以這樣做
Node<E> previousNode = null;
Node<E> currentNode = head;
int currentIndex = 0;
while(currentIndex < t) {
previousNode = currentNode;
currentNode = currentNode.getNext();
currentIndex++;
}
if (previousNode == null) { //removing first node
head = head.getNext();
} else {
previousNode.setNext(currentNode.getNext());
}
size--;
return currentNode.getElement();
但無論如何,您需要將其作為特殊情況處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.