📄 demo_struct_list_b.cpp
字号:
//***************************************************
//*************************************
//** Struct_List_B.cpp **
//*************************************
// 输入和创建链表,最后输出显示该链表
# include <iostream.h>
# include <stdlib.h>
//***************************************************
// 声明结构体
struct Student
{
long number;
float score;
Student* next;
};
//***************************************************
// 定义创建链表的函数
Student* Create()
{
Student* head; // 链表的头指针
Student* pS; // 链表的结点指针
Student* pEnd; // 链表的尾指针
// 新建一个结点
pS= new Student; // 动态申请一个结点内存空间
if(pS==NULL)
{
cout<<"Can't allocate more memory,terminating.\n";
exit(1);
}
cout<<"Input number and score of one item:\n";
cin>>pS->number>>pS->score; // 给节点赋number和score值
head=NULL; // 开始链表为空
if(pS->number==0) // 若链表为空
{
delete pS;
return head;
}
while(pS->number!=0) // 若链表为非空
{
if(head==NULL)
head=pS;
else
pEnd->next=pS; // 给节点赋next值
pEnd=pS;
// 新建一个结点
pS=new Student; // 动态申请一个结点内存空间
if(pS==NULL)
{
cout<<"Can't allocate more memory,terminating.\n";
exit(1);
}
cout<<"Input number and score of one item:\n";
cin>>pS->number>>pS->score; // 给节点赋number和score值
}
pEnd->next=NULL; // 给节点赋next值
delete pS;
return head;
}
//***************************************************
// 定义遍历链表的函数
void ShowList(Student* head)
{
if(!head)
{
cout<<"The list is null!\n";
return;
}
cout<<"Output the items of list are \n";
while(head)
{
cout<<head->number<<","<<head->score<<endl;
head=head->next;
}
return;
}
//***************************************************
// 删除链表结点
Student* Delete(Student* head,long number)
{
Student* p;
// 若链表是空的
if(!head) // head==NULL
{
cout<<"\nList null!\n";
return head;
}
// 若删除的结点是第一个结点
if(head->number==number)
{
p=head;
head=head->next;
delete p;
cout<<number<<" have been deleted!\n";
return head;
}
// 若删除的结点不是第一个结点
// 循环执行条件是: pGuard->next!=NULL
for(Student* pGuard=head;pGuard->next;pGuard=pGuard->next)
{
if(pGuard->next->number==number)
{
p=pGuard->next; // 待删除的结点
pGuard->next=p->next;
delete p;
cout<<number<<" have been deleted!\n";
return head;
}
}
cout<<number<<" not found!\n"; // 未找到要删除的结点
return head;
}
//***************************************************
// 主程序创建并遍历链表
void main()
{
Student* head;
head=Create();
ShowList(head);
head=Delete(head,54);
ShowList(head);
}
//***************************************************
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -