#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student
{ long num;
float score;
struct student*next;
};
int n; //结点个数
int main()
{ struct student *creat(void);
struct student *del(struct student *head,long num);
struct student *insert(struct student*head,struct student*stu);
void print(struct student*head);
long num;
struct student *head,stu;
printf("input records:\n");
head=creat();
printf("enter the integer you want to del:\n");
scanf("%ld",&num);
head=del(head,num); //有head后面的结点都可访问
printf("enter the stu you want to insert :\n"); //输入想要插入的结点,p1;
scanf("%ld,%f",&stu.num,&stu.score);
head=insert(head,&stu); //实参为指针型,可以改变实参的值(...)
print(head);
}
//p1就像前锋往前冲,p2在后方负责结点的缝合,首先考虑head的指向,毕竟返回的是head
struct student *creat(void)
{ struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(LEN);
scanf("%ld,%f",&p1->num ,&p1->score );
head=NULL;
while(p1->num!=0)
{ n=n+1;
if(n==1) head=p1; //第一个结点;
else p2->next=p1; p2=p1; //用p2来连接两个结点
p1=(struct student *)malloc(LEN); //新开辟结点
scanf("%ld,%f",&p1->num ,&p1->score); //对结点输入数据
}
p2->next =NULL;
return head; //链表已经构建完成,只需head,下同
}
//删除结点的函数
struct student *del(struct student *head,long num) //删除num;
{ struct student *p1,*p2;
if(head==NULL)
{ printf("list NULL!\n");
return head;}
p1=head;
while(p1->num!=num && p1->next !=NULL) //p1不能是最后一个结点,不然while语句无法执行
{ p2=p1; p1=p1->next; } //p2总是比p1慢一步
if(p1->num==num)
{ if(head==p1) head=p1->next; //最先考虑head
else p2->next=p1->next ; //p2又来连接结点了
n=n-1;
}
return head;
else printf("num not been found!\n"); //接while语句,都最后一个结点了还没找到该删除的结点,找不到了。
}
//插入结点的函数
struct student *insert(struct student*head,struct student*stu)
{ struct student *p1,*p2,*p3;
p1=head;
p3=stu;
if(head==NULL) //为空链表,插入一个结点,记得最后指向NULL,一个链表得完整
{ head=p3;p3->next=NULL;}
else
{ while((p1->num<p3->num) && (p1->next!=NULL))
{ p2=p1;
p1=p1->next;
}
if(p1->num>=p3->num)
{ if(head==p1) head=p3; //在head前插入
else p2->next=p3; //p3在p2后,p1前。p2缝好和p3。
p3->next =p1; //p3缝好p3和p1。
}
else
{ p1->next =p3; p3->next =NULL;} //在p1后插入,并使p3变为表尾,收工
}
n=n+1;
return head;
}
void print(struct student*head)
{
struct student*p;
printf("num and score is:\n");
p=head;
if(head!=NULL)
while(p!=NULL)
{ p=p->next;
printf("%ld,%5.1f",p->num ,p->score );
}
printf("\n");
}