C ++删除链表中的元素

时间:2018-09-28 06:36:04

标签: c++ linked-list

我正在尝试为我的代码编写一个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;
        }
    }

};

2 个答案:

答案 0 :(得分:0)

如果要删除第一个元素,则需要更新Root

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

您也无法确保是否至少有ind个节点。

答案 1 :(得分:0)

查看代码中的注释:

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 /编译器检查代码,如果发现错误,请随时自行修复...)