双链表插入和显示以及搜索和删除

时间:2014-05-07 14:47:28

标签: c++

我正在实现一个双向链表,我的搜索和删除功能给了我一个错误。 我是双重链接列表的新手,所以任何帮助都会受到赞赏。

这是我的插入功能。

void push(student s)
{

   if ( head == NULL)
   {
       node *tmp = new node;
       tmp->data = s;
       tmp->next = NULL;
       tmp->prev = NULL;
       head = tmp;
       tail = tmp;
   }
    else if ( head != NULL)
    {
        node *tmp = new node;
        tmp->data = s;
        tmp->next = head;
        head->prev = tmp;
        head = tmp;
    }



}

这是我的显示功能

void display()
{
    node *current = head;

    while (current!=NULL)
    {
        cout << current->data.name << endl;
        cout << current->data.GPA << endl;
        cout << current->data.id << endl;
        cout << current->data.university << endl;
        current = current->next;
    }
}

这是我的删除

void removeStudent(int id)
    {
    //loop through list to find id
    node *current = head;

    while ( head != NULL)
    {
        //go through all data



        //find data that matches id
        if ( current->data.id == id)
        {
            //delete the match
            node *trash;
            trash = current;
            current->prev->next = current->next;
            current->next->prev = current->prev;

            delete trash;


        }
        else{
            current = current->next;
        }

    }

}

这是我的主要

int main()
{

    student me;
    student you;
    you.id = 9;
    you.GPA = 9.8;
    you.name = "peter";
    you.university = "stc";
    me.id = 20;
    me.GPA = 20.0;
    me.name = "robert";
    me.university = "utpa";
    student mee;
    mee.id = 15;
    mee.GPA = 8.9;
    mee.name = "mike";
    mee.university = "utpa";
    studentList list;
    list.push(me);
    list.push(you);
    list.push(mee);
    list.pop();
    list.removeStudent(15);
    list.display();

    return 0;
}

2 个答案:

答案 0 :(得分:2)

问题在于您的push功能。您可以大大简化它以避免出现条件逻辑问题:

void push(student s)
{
   node *tmp = new node;
   tmp->data = s;
   tmp->next = head; // this works even when head is NULL
   tmp->prev = NULL;

   if (head == NULL)
   {
       head = tmp;
       tail = tmp;
   }
   else
   {
       head->prev = tmp;
       head = tmp;
   }
}

答案 1 :(得分:-1)

if ( head == NULL)
{
   ...
   head = tmp;
}
if ( head != NULL)
{
    ...
    head = tmp;
}

您检查head是否为NULL,如果是,请指定head。然后,检查head是否 NULL,此时它绝对不是您在上面指定的,然后执行其他操作。

简单的解决方案,将两个if结构更改为if ... else if,例如

if ( head == NULL)
{
   ...
   head = tmp;
}
else if ( head != NULL)
{
    ...
    head = tmp;
}