单向链表的排序、查找、插入、删除
/***************************************
* 使用单向链表 *
* 按学生成绩从高到低的顺序存储学生信息 *
* 从中删除不及格学生的信息 *
***************************************/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
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;
}
}
int main ()
{
NODE *newp,*head,*p;
char name[20];
float score,low=60;
if((newp=new NODE)==NULL)
{
cout<<"no 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<<"no 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;
}
cout<<"Before delete:"<<endl;
DispList(head);
for (p=Search(head,low);p->next!=NULL;p=Search(head,low))
DelNode(p);
cout<<"after delete:"<<endl;
DispList(head);
DelList(head);
return 0;
}