c ++,使用id删除节点

时间:2018-12-17 07:12:19

标签: c++ linked-list queue

我有一个成员类,我想在其中使用ID删除节点。我为链表创建了一个结构。所有其他功能均正常运行,但无法删除给定位置的节点。当我添加成员并显示它时,它工作正常,但是在删除节点时,它不起作用。

#include <iostream>

#include <string>

class member {

public:
    struct nodetype {
        int id;
        string name;
        string password;
        string type;
        nodetype* next;
    };

    member() {
        start = NULL;
    }

    void addMember(int x, string n, string p, string t) {
        nodetype* temp = new nodetype();
        temp->id = x;
        temp->name = n;
        temp->password = p;
        temp->type = t;
        temp->next = start;
        start = temp;
    }
    void showMember()
    {

        nodetype* temp = start;
        while (temp != NULL)
        {
            cout << temp->id << "\t" << temp->name << "\t" << temp->type << "\t" << temp->password << endl;
            temp = temp->next;
        }
    }

    void deleteMember(int x)
    {
        nodetype* tmp = start;

        while (tmp != NULL)
        {
            if (tmp->id == x)
            {
                nodetype* del = tmp;
                start->next = tmp->next;
                delete del;
            }
        }
    }
private:
    nodetype* start;
};

int main()
{
    member obj;

    obj.addMember(1,"joe","123","student");
    obj.addMember(2,"john","456","staff");
    obj.deleteMember(2);
    obj.showMember();


}

1 个答案:

答案 0 :(得分:2)

首先在deleteMember函数中,您不会向前移动tmp。您可以这样做-

void deleteMember(int x)
{
    nodetype* tmp = start;
    nodetype* prv = NULL;
    while (tmp != NULL)
    {
        if (tmp->id == x)
        {
           if(prv != NULL)
           {
                prv->next=tmp->next;
           }
           else
           {
                start=tmp->next;
           }
           delete tmp;
           break;
        }
        prv=tmp;
        tmp=tmp->next;
    }
}