p5_13b.cpp
来自「相当丰富的C++源码」· C++ 代码 · 共 85 行
CPP
85 行
/*************************************
* p5_13.cpp *
* 单向链表排序、查找、插入、删除 *
**************************************/
#include <iostream>
using namespace std;
struct student
{
char name[20];
float score;
struct student *next;
};
typedef student NODE;
NODE *Search(NODE *head, int key) { //查找关键字小于key的节点的前驱;
NODE *p;
p=head;
while(p->next!=NULL) {
if(p->next->score<key)
return p;
p=p->next;
}
return p;
}
void InsertNode(NODE *p,NODE *newp) { //在p之后插入节点newp
newp->next=p->next;
p->next=newp;
}
void DelNode(NODE *p) { //删除p节点的一个后继节点
NODE *q;
if(p->next!=NULL) {
q=p->next;
p->next=q->next;
delete q;
}
}
void DelList(NODE *head) { //销毁整个链表
NODE *p;
p=head;
while(head->next!=NULL) {
head=head->next;
delete p;
p=head;
}
delete head;
}
void DispList(NODE *head) { //显示链表各元素
NODE *p;
p=head;
while(p->next!=NULL) {
cout<<p->next->name<<"\t"<<p->next->score<<endl;
p=p->next;
}
}
void main()
{
NODE *newp,*head,*p;
char name[20];
float score,low=60;
if((newp=new NODE)==NULL) {
cout<<"new NODE fail!"<<endl;
exit(0);
}
head=newp;
head->next=NULL;
cout<<"Input name and score(-1 to exit):"<<endl;
cin>>name>>score;
while(score>0) {
if((newp=new NODE)==NULL) {
cout<<"new NODE fail!"<<endl;
exit(0);
}
strcpy(newp->name,name);
newp->score=score;
newp->next=NULL;
p=Search(head,score);
InsertNode(p,newp);
cin>>name>>score;
}
DispList(head);
for(p=Search(head,low);p->next!=NULL;p=Search(head,low))
DelNode(p);
cout<<"after delete:"<<endl;
DispList(head);
DelList(head);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?