动态链表的建立
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n; //全局变量
struct Student creat(void) //定义建立动态链表的函数,次函数返回指向链表头的指针。
{
struct Student *head,*p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN) //开辟一个新单元。malloc函数返回开辟的新单元首地址。
scanf("%d %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;
p1= (struct Student *)malloc(LEN);
scanf("%d %f",&p1->num,&p1->score) //输入其他学生的学号和成绩。
}
p2->next=NULL;
return(head);
} ;
void print(struct Student *head) //定义输出链表函数
{
struct Student *p;
printf("\nNow,these %d records are:\n",n);
p=head;
if(head!=0)
do
{
printf("%ld,%5.lf\n",p->num,p->score);
p=p->next;
}while(p!=NULL)
}
int main()
{
struct Student *pt;
pt=creat(); //调用creat函数
print(head); //调用print函数
return 0;
}
链表的删除
struct student *del(struct student *head,long num)
{
struct student *p1,*p2;
if (head==NULL) {printf("\nlist null!\n");goto end;}
p1=head;
while(num!=p1->num && p1->next!=NULL)
{p2=p1;p1=p1->next;}
if(num==p1->num)
{
if(p1==head)
head=p1->next;
else p2->next=p1->next;
printf("delete:%ld\n",num);
n=n-1;
}
else printf("%ld not been found!\n",num);
end;
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(head==p1) head=p0;
else p2->next=p0;
p0->next=p1;
}
else {p1->next=p0; p0->next=NULL;}}
n=n+1;
return(head);
}