学习过程中写的,就当复习基础知识好了。
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
//#define NULL 0
struct student
{
long num;
float score;
struct student *next;
};
int n;
struct student *creat(void) /*创建动态链表*/
{
struct student *p1,*p2,*head;
p1=p2=(struct student *) malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
n=0;
while(p1->num!=0)
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=( struct student *)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head,long num) //删除链表节点
{
struct student *p1,*p2;
if(head==NULL)
{
printf("空链表!/n");
return head;
}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(p1==head) head=p1->next;
else p2->next=p1->next;
printf("delete %d successfully!/n",num);
}
else printf("not found the num!");
return head;
}
struct student *insert(struct student *head,struct student *stud) //插入一个节点。
{
struct student *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)
head=p0,p0->next=NULL;
else
{
while(((p0->num)>(p1->num))&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(p1==head) head=p0,p0->next=p1;
else p2->next=p0,p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
return head;
}
void main()
{
long num;
struct student *p,*head,stud;
head=p=creat();
do
{
printf("%ld,%.2f/n",p->num,p->score);
p=p->next;
}
while(p!=NULL);
printf("input the num you want to delete:/n");
scanf("%ld",&num);
p=del(head,num);
do
{
printf("%ld,%.2f/n",p->num,p->score);
p=p->next;
}
while(p!=NULL);
printf("input the inserted record:/n");
scanf("%ld,%f",&stud.num,&stud.score);
p=insert(head,&stud);
do
{
printf("%ld,%.2f/n",p->num,p->score);
p=p->next;
}
while(p!=NULL);
}