删除链表C++中的节点
所以我一直在搜索论坛,但我对语言和链接列表仍然很陌生,所以我几乎无法破译结果.
So I've been searching forums, but im still very new to the language and linked lists so I can barely decipher the results.
基本上我为我的链表做了一个删除功能.我目前可以创建一个列表,遍历列表,对列表进行排序,搜索列表,并在链表中的任何节点之前插入.我从插入中回收了一些代码来定位列表中可以删除的点.我的主要困惑点是如何将前面的点链接到我要删除的节点之后的节点.
basically I made a delete function for my linked list. I can currently Create a list, traverse the list, sort the list, search the list, and insert before any node in the linked list. I recycled some code from the insert to locate the point in the list where I could delete. My main point of confusion is how to link the previous points to the node that is after the one I am deleting.
推荐答案
我不会写一个全新的链表实现,但我可以为你指出代码中的一些问题.
I won't write a whole new linked list implementation but i can point out some of the problems with the code for you.
诀窍是在要删除的节点之前保留一个节点.
The trick is to stay one node ahead of the one you want to delete.
为了清晰起见,我已将 entry
重命名为 current
I have renamed entry
to current
for clarity
nodetype *current , *first, *next;
int akey;
// With this line your search will start from the second element.
// current =start->ptr;
// Should be
current = start;
// this is not needed. I am assuming the last node has NULL value for '->ptr'
// last=start;
next = current->ptr;
cout<<"Input Data You Would Like To Delete"<<endl;
cin>>akey;
// Check if the first node contains the data
// Assuming the list will have at least one element. i.e. current is not NULL
while (current->adata == akey)
{
// Delete it.
delete current;
// Update current for the while loop
current = next;
// update next too.
next = current->ptr;
}
// Now we know the first element doesn't contain the data.
// Update the pointer to the begging of the new list if anything is removed from the top.
first = current;
// This has unnecessary checks.
// ****Specifically (akey!=current->adata) will
// prevent you from entering the loop if it is false.
// while((akey!=current->adata)&&(current->ptr !=NULL))
while(next != NULL) // This should be enough
{
if(next->adata == akey)
{
// make the current node (before the 'deletion point')
// lined to the one after the 'deletion point (next of the next)
current->ptr = next->ptr;
// delete the node.
delete next;
// Make the next pointer point to the new next.
next = current->ptr
}
// Otherwise advance both current and next.
else {
current = next;
next = next->ptr;
}
}
// Use this to test it.
current = first;
while(current){
cout<<current->adata<<", ";
current = current->ptr;
}
这不是最干净的方式.但是,它与您的实现类似,因此您可以看到哪里出错了.
This is not the cleanest way. However it is similar to your implementation so you can see where you went wrong.
相关文章