关于C++链表的一个小问题,求指教
当删除头结点的时候程序崩溃了 为什么啊?
# include<iostream>
using namespace std;
struct book
{
public:
int num;
float price;
book *next;
};
book *head = NULL;
book *create()
{
book *p1,*p2;
p1 = new book;
head = p1;
p2 = p1;
cout<<"请输入图书编号,以0结束\n";
cin>>p1->num;
if(p1->num != 0)
{
cout<<"请输入图书的价格\n";
cin>>p1->price;
}
else
{
delete p1;
p2 = NULL;
p2->next = NULL;
head = NULL;
head->next = NULL;
return head;
}
while(p1->num != 0)
{
p2 = p1;
p1 = new book;
cout<<"请输入图书编号,以0结束\n";
cin>>p1->num;
if(p1->num != 0)
{
cout<<"请输入图书的价格\n";
cin>>p1->price;
}
p2->next = p1;
}
delete p1;
p2->next = NULL;
return head;
}
void showbook(book *head)
{
cout<<"编号"<<" "<<"价格"<<endl;
while(head)
{
cout<<head->num<<" "<<head->price<<endl;
head = head->next;
}
}
void Delete(book *head,int num)
{
book *l;
if(head->num == num)
{
l = head;
head = head->next;
delete l;
cout<<"删除操作成功!\n";
return;
}
while(head)
{
if(head->next == NULL)
{
cout<<"未找到要删除的编号\n";
return;
}
if(head->next->num == num)
{
l = head->next;
head->next = l->next;
delete l;
cout<<"删除操作成功\n";
return;
}
head = head->next;
}
cout<<"未找到要删除的编号\n";
}
int main()
{
int denum;
book *head = NULL;
head = create();
showbook(head);
cout<<"请输入要删除的编号\n";
cin>>denum;
Delete(head,denum);
showbook(head);
return 0;
}
[解决办法]
- C/C++ code
# include<iostream>using namespace std;struct book{public: int num; float price; book *next;};book *head = NULL;book *create(){ book *p1,*p2; p1 = new book; head = p1; p2 = p1; cout<<"请输入图书编号,以0结束\n"; cin>>p1->num; if(p1->num != 0) { cout<<"请输入图书的名字及价格\n"; cin>>p1->price; } else { delete p1; p2 = NULL; p2->next = NULL; head = NULL; head->next = NULL; return head; } while(p1->num != 0) { p2 = p1; p1 = new book; cout<<"请输入图书编号,以0结束\n"; cin>>p1->num; if(p1->num != 0) { cout<<"请输入图书的名字及价格\n"; cin>>p1->price; } p2->next = p1; } delete p1; p2->next = NULL; return head;}void showbook(book *head){ cout<<"编号"<<" "<<"价格"<<endl; while(head) { cout<<head->num<<" "<<head->price<<endl; head = head->next; }}//注意这个函数参数类型void Delete(book **head,int num){ book *l; if((*head)->num == num) { l = *head; *head = (*head)->next; delete l; cout<<"删除操作成功!\n"; return; } while(*head) { if((*head)->next == NULL) { cout<<"未找到要删除的编号\n"; return; } if((*head)->next->num == num) { l = (*head)->next; (*head)->next = l->next; delete l; cout<<"删除操作成功\n"; return; } *head = (*head)->next; } cout<<"未找到要删除的编号\n";}int main(){ book *head = NULL; int denum; head = create(); showbook(head); cout<<"请输入要删除的编号\n"; cin>>denum;//注意传参类型 Delete(&head,denum); showbook(head); return 0;}
[解决办法]
因为你的头结点删除,你的整个链表就丢失了,所以真正的删掉头结点就是把头结点指向head=head->next;就行了