[英]Delete the element at index N, LinkedList
這是功課
我被要求從LinkedList中刪除第k個元素。 我還給了它一個大小int N
問題是刪除位置“ k”的節點后如何更新列表的大小? 如果我的代碼中的邏輯有問題,請提及。
我不希望解決方案只是指導,謝謝。
int N;
Node first;
// delete the kth element (where k is between 0 and N-1 inclusive)
public void delete (int k) {
if (k < 0 || k >= N)
throw new IllegalArgumentException();
Node x = first;
if( k == 0){
first = x.next;
N = N - 1;
}
for(int i = 1; i < k; i++){
x = x.next;
N = N - 1;
}
x.next = x.next.next;
N = N - 2;
}
我認為清單大小(int N)可能做錯了。
當你刪除一個節點,你只需要改變以前的Node
的next
在K和遞減的(新)下一個節點N
( N--
)來更新列表的大小。
編輯
還要注意您的for循環,您要更改節點k
之前的所有下一個節點
請考慮兩種情況:k == 0,其余情況。 大小由N給出,因此新大小應為N-1。
Node x = first; // What a name
if (k == 0) {
first = x.next; // Could be first = first.next
N = N - 1;
// Are you done here?
}
for (int i = 1; i < k; i++) {
x = x.next;
// Really? N = N - 1;
}
x.next = x.next.next;
// Really? N = N - 2;
N = N - 1;
嘗試使用LinkedList中定義的list.remove(Object obj)
方法。 要使對象位於第k個元素,可以使用list.get(int index)
。 一旦找到第k個元素,請考慮中斷或返回以避免任何並發的修改問題或與索引相關的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.