C++删除链表中的元素



我正在尝试为我的代码编写一个Remove_Node函数,但在删除第一个和最后一个元素时遇到问题。不知何故,这段代码不起作用。如果我删除中间的元素,假设 3 然后是第一个,结果不正确。另外,如何处理最后一个元素?

void Remove_Node(int ind) {
LNode *tmp = Root;
LNode *tmp1;
if (Root->Next == NULL){
delete Root;
}
else if (ind == 1){
tmp1 = tmp;
tmp->tmp.Next;
delete tmp1;
}
else{
for (int i=1; i<ind-1; i++) tmp = tmp->Next;
tmp1 = tmp->Next->Next;
delete tmp->Next;
tmp->Next = tmp1;
}
}

};

在删除第一个元素的情况下,您需要更新Root

else if (ind == 1){
tmp1 = tmp;
tmp->tmp.Next;
delete tmp1;
Root = tmp;

此外,您不能确保是否至少有ind个节点。

请参阅代码中的注释:

void Remove_Node(unsigned int ind)
// (if you use unsigned, you don't have to check for < 0)
{
LNode* tmp = Root;
if(!tmp) // check, if the list is empty
{
// whatever index, we are out of range...
// -> some error handling, e. g. throwing an exception:
throw std::out_of_range("whatever...");
}
else if(ind == 0) // first element in list -> need to adjust Root!
{
Root = root->Next; // will get nullptr if no further elements
delete tmp; // delete original root
}
else
{
//for (int i = 0; i < ind - 1; i++)
// this is simpler in given case:
while(--ind)
{
if(!tmp->Next) // there is no successor to delete...
throw std::out_of_range("whatever...");
tmp = tmp->Next;
}
// now tmp points to one node before the one to delete
LNode* tmp1 = tmp->Next;
if(!tmp1) // no successor!
throw std::out_of_range("whatever...");
tmp->Next = tmp1->Next; // getting nullptr if tmp1 has no successor
delete tmp1;
}
}

(代码不是通过IDE/编译器检查的,如果你发现一个错误,请随时自己修复它......

相关内容

  • 没有找到相关文章

最新更新