删除循环链接列表中的项目
deleting an item in cicular linked list
我的程序应该做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方法上,其中可能没有分配正确的指针。
然后,为什么系统("暂停")?看看这里。
相关文章:
- 从链接列表c++中删除一个项目
- 如何维护资源管理器项目视图中当前可见的项目列表
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 在给定的项目列表上实现搜索?
- 从文本文件读取,然后将项目存储到列表中
- 在修改项目列表时,请防止可编辑的Qcombobox选择更改
- 发送 QML 项目列表C++类连接到 QML :M16 错误
- 当SLIST_ENTRY不是项目列表的第一个成员时,使用单向链表
- 项目列表中的组合
- C ++ win 32,我想将项目列表添加到组合框中.我该怎么做
- 当试图在C++eclipse工作区中导出一个团队集(5个项目)时,项目列表是空的
- 随机化项目列表并将其输出到文本文件
- Eclipse CDT 自动更新/同步项目列表(以方便"refresh"相关项目集)
- 在每次迭代中以不同顺序循环遍历项目列表
- “添加到项目列表”是灰色的Qt项目管理对话框
- 从 std::vector<std::vector 中删除任意项目列表<T> >
- QT:来自多个旋转框的项目列表
- QComboBox动态项目列表
- QComboBox 不显示其项目列表
- 在浏览项目列表时保存多个项目的数据