[英]Delete list of Singly linked list
我正在練習數據結構,並且實現了一個代碼,該代碼創建一個單鏈接列表,添加到列表中並刪除列表。 我真的很想知道我的刪除列表功能是否真正在做它應該做的事情。 我認為這是因為刪除后我嘗試打印列表時會崩潰。 因此,有關確保其刪除我的列表的任何建議,或者您對改進我的代碼可能有的其他建議。 在動態分配內存方面,我還是個菜鳥。
typedef struct node {
int data;
node* next;
}* nodePtr;
nodePtr addToList(nodePtr head, int data) {
nodePtr newItem = new node; //create a new item
newItem->data = data; //assign the data to the new item
newItem->next = head; //point to head
return newItem; //return the new head
}
void deleteList(nodePtr head) {
if (head == nullptr) {
return;
}
else {
deleteList(head->next);
delete head;
head = nullptr;
}
}
void Print(nodePtr n) {
while (n != nullptr) {
cout << n->data << " ";
n = n->next;
}
}
int main() {
nodePtr head = new node;
nodePtr second = new node;
nodePtr third = new node;
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
Print(head);
cout << endl;
head = addToList(head, 0);
Print(head);
cout << endl;
deleteList(head);
return 0;
}
你打電話時:
deleteList(head);
該語句后, head
將不等於NULL
。 相反,您需要執行以下操作:
deleteList(head);
head = NULL;
要么:
void deleteList(nodePtr & head) {
if (head == nullptr) {
return;
}
else {
deleteList(head->next);
delete head;
head = nullptr;
}
}
請注意,我們對deleteList使用參考參數。
除了比爾答案中指出的一些小警告外,您的功能大部分是正確的。
我只想指出,您確實不需要遞歸刪除列表。 這是另一種方法。
while(head != nullptr) {
node *deleteMe = head;
head = head->next;
delete deleteMe;
}
我將添加類似以下內容來清理代碼:
nodePtr create_node(int n) {
nodePtr p = new node;
assert (p != NULL);
p -> data = n;
p -> next = NULL;
}
這樣,您可以使用如下循環來清理主要功能以進行測試:
for (int i = 0; i < 10; ++i) {
nodePtr p = create_node(i);
head = addToList(head, p);
}
然后通過引用傳遞您的頭部指針,這樣您將得到如下結果:
nodePtr addToList(nodePtr&head, nodePtr newItem) {
newItem->next = head; //point to head
head = newItem;
}
這些幾乎只是樣式更改,但它使測試程序變得更容易,而不是在主函數中單獨創建節點,這使代碼看起來更簡潔。 您可以做的另一件事是,一旦實現遞歸刪除可能更有意義,則嘗試首先迭代刪除此列表。
要進行實際調試並檢查是否正確地分配了內存,最好的方法是使用調試器,您可以添加assert()以驗證空值,但是值得檢查一下gdb之類的東西(對於命令行): https: //www.cs.cmu.edu/~gilpin/tutorial/ 。 該教程實際上是用於調試鏈表的內存分配的,因此可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.