64,648
社区成员
发帖
与我相关
我的任务
分享
#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;
}