![](/img/trans.png)
[英]linked list : how to delete last node, where we have pointer to last node in a single linked list
[英]How can I delete an node from a linked list with a single pointer?
我研究的這本書#include
一個練習,要求我們修改以下代碼,該代碼從鏈表中刪除一個節點,並構建另一個僅用一個指針執行完全相同操作的函數:
struct node {
int value;
struct node * next;
};
struct node delete_from_list( struct node * list , int n){
struct node *cur, *prev;
for (cur = list, prev = NULL;
cur != NULL && cur -> value != n;
prev = cur, cur -> next)
;
if(cur == NULL)
return list;
else if(prev == NULL)
list = list -> next;
else
prev -> next = cur -> next;
free(cur);
return list;
}
我在網上看到的一些代碼是:
struct node *delete_from_list(struct node **list, int n) {
struct node *entry = *list;
while (entry) {
if (entry->value == n) {
*list = entry->next;
free(entry);
break;
}
list = &entry->next;
entry = entry->next;
}
return *list;
}
但我對此有兩個反對意見:
這段代碼實際上包含兩個指針entry
和list
。
我們是free()
輸入entry
但繼續使用它“感覺”像一個錯誤。
請,如果您願意提供幫助,請解釋我的反對意見或編寫新代碼。 謝謝。
- 這段代碼實際上包含兩個指針
entry
和list
。
您需要構建一個使用單個指針的算法。 在您的情況下,盡管看起來像兩個,但entry
是算法使用的一個指針,除了list
之外,它實際上是包含 algorithm的函數的輸入。
- 我們是
free()
輸入條目,但繼續使用它“感覺”像一個錯誤。
該代碼在釋放它后不使用entry
。 一旦釋放,循環立即中斷,因為break
語句在調用free
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.