C++链表节点删除问题

rere02 rere02 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如下:


#include<iostream>
using namespace std;

struct book
{
int num;
float price;
book *next;
};

book *head = NULL;
book *creat()
{
book *p1, *p2;
p1 = new book;


cout <<"请输入图书编号,以0结束:";
cin >> p1->num;
if(p1->num != 0)
{
head = p1;
p2 = p1;
cout << "请输入图书价格:" ;
cin >> p1->price;
}
else
{
delete p1;
//p2->next = NULL;
return head;
}
while(p1->num != 0)
{
p2 = p1;
p1 = new book;
cout <<"请输入图书编号,以0结束:";
cin >> p1->num;
if(p1->num != 0)
{
cout << "请输入图书价格:" ;
cin >> p1->price;
}
p2->next = p1;
}
delete p1;
p2->next = NULL;
return head;
}

void print(book *head)
{
cout << endl;
while(head)
{
cout << "图书编号为:" << head->num <<"\t";
cout << "图书价格为:" << head->price << "\t";
head = head->next;
cout << endl;
}
}

void delete1(book *head, int num)
{
book *l;
if(head->num == num) //输入的编号为第一个节点时
{
l = head;
::head = head->next;
delete l;
cout << "操作成功"<< endl;
return;
}
while(head)
{
if(head ->next == NULL)
{
cout << "找不到输入的编号节点" << endl;
return;
}

if(head->next->num == num)
{
l = head->next;
head->next = l->next;
delete l;
cout << "操作成功" << endl;
return;
}
head = head->next;

}
cout << "找不到输入的编号节点" << endl;
}
int main()
{
book *a;
a = creat();
print(a);
cout << "请输入要删除的节点图书编号:" << endl;
int booknum;
cin >> booknum;
delete1(a, booknum);
print(a);
return 0;
}



当我删除第一个节点的时候,后面的节点不会往上移;
各位大吓帮忙看看,小弟先谢了~~~
...全文
评论 11
收藏 已收藏
分享
返回顶部
rere02
C++ 语言 65,212 成员 250,513 内容