删除循环链接列表中的项目

deleting an item in cicular linked list

本文关键字:项目 列表 循环 链接 删除      更新时间:2023-10-16

我的程序应该做3个操作:

  1. 插入
  2. 删除
  3. 显示在循环链接列表中

我的问题是删除功能。这是代码:

void c_list::del()
{
    int num;
    if(isempty())
        cout<<"List is Empty!"<<endl;
    else
    {
        node *temp1=first;
        node *temp2=NULL;
        cout<<"Enter the number that u want to DELETE:"<<endl;
        cin>>num;
        while(temp1->next!=first && temp1->info != num)
        {
            temp2=temp1;
            temp1=temp1->next;
        }
        if(num != temp1->info )
            cout<<"your number was not found in the list"<<endl;
        else
        {
            if(temp2!=NULL)
            {
                temp2->next=temp1->next;
                cout<<temp1->info<<" was deleted"<<endl;        
            }
            else
            {
                first=temp1->next;
                cout<<temp1->info<<"was deleted"<<endl;
            }
        }
    }
    system("pause");
}

删除功能是这样工作的:用户输入一个数字,程序搜索该数字&找到号码后,将其从列表中删除。

现在的问题是,当用户输入列表中不存在的号码时,会出现"应用程序崩溃窗口"(我的意思是这个窗口:程序没有响应),而我为这种情况提供了一条错误消息("在列表中找不到您的号码")!!

你能告诉我问题出在哪里吗?

您的插入例程并没有创建循环列表。当列表为空并且首先插入初始项时==NULL。在这种情况下,您的代码使列表处于非圆形状态。因为:

    newitem->next=first;
    if(first==NULL)
        first=newitem;

此时first->next==NULL,循环列表中不应该出现这种情况。只要列表中不存在要查找的项目,您的搜索代码就会失败。这是因为它从不循环回第一个节点,因为列表不是循环的。

我认为在while循环中,您已经到达了列表的末尾在行下temp1变为NULL之后。

temp1=temp1->next;

然后您试图从空指针读取信息属性,这会导致错误。

if(num!=temp1->info)

我知道你说这是循环清单,但我不确定它是否正确实施。我的建议是在while循环后打印temp1->info,以确保列表和实现的正确性。

如果您插入一个不在列表中的数字,则在第一个while中有一个循环。

因此:

node* temp1 = first;
node* temp2 = 0; 
while(temp1->next!=first && !temp2) {
  if(temp1->info == num) {
     /* save pointer and exit from while */
     temp2 = temp1;
  } else {
    temp1 = temp1->next;
  }
}

然后你的代码会产生垃圾,因为你从来没有调用过delete。

问题很可能出在insert方法上,其中可能没有分配正确的指针。

然后,为什么系统("暂停")?看看这里。