链表对于C语言的学习者来说是一大难点,但链表又是学好数据结构的基础。在此,对单链表的创建、输出、结点的插入、结点的删除进行简要介绍。
1、首先定义一个结构体数组
#define LEN sizeof(struct student)
struct student
{
int num;
char name[20];
float score;
struct student *next;
};
int n;
2、单链表的创建
struct student *creat(void)//创建链表
{
n=0;
struct student *p1,*p2,*head;
head=NULL;
p1=p2=(struct student *)malloc(LEN);//开辟新单元
scanf("%d,%s,%f",&p1->num,&p1->name,p1->score);//输入数据
while(p1->num!=0)//限定当num为0时,链表输入结束
{
n++;
if(n==1)head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d,%s,%f",&p1->num,&p1->name,p1->score);
}
p2->next=NULL;
return head;
}
3、单链表的输出
void print(struct student *head)//输出链表
{
printf("\nthere are %d records\n",n);
struct student *p;
p=head;
if(head!=NULL)
do
{
printf("%d,%s,%.0f\n",p->num,p->name,p->score);
p=p->next;
}
while(p!=NULL);
}
4、单链表结点删除
struct student *del(struct student *head,int num)//删除一个节点
{
struct student *p,*p1;
p=head;
if(head==NULL)//当链表为空时
{
printf("this table is null\n");
goto end;
}
while(num!=p->num&&p->next!=NULL)//判断链表中是否存在该结点
{
p1=p;
p=p->next;
}
if(num==p->num)//当结点存在时
{
if(p==head)head=p->next;
else
p1->next=p->next;
printf("delete\n");
n--;//链表中结点个数
}
else
printf("not find");//找不到该结点时
end: return head;
}
5、单链表的插入
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++;
return(head);
}
6、main主函数
int main(int argc, char *argv[]) {
struct student *head,*stu;
int del_num;
printf("input record:\n");//创建链表
head=creat();
print(head);//输出链表
printf("input the deleted number:\n");//删除链表
scanf("%d",&del_num);//输入要删除的记录
while(del_num!=0)
{
head=del(head,del_num);
print(head);
printf("input the deleted number:\n");
scanf("%d",&del_num);
}
printf("input the inserted record:\n");//插入结点
stu=(struct student *)malloc(LEN);
scanf("%d,%s,%f",&stu->num,&stu->name,&stu->score);
while(stu->num!=0)
{
head=insert(head,stu);
print(head);
printf("input the inserted record:\n");
stu=(struct student *)malloc(LEN);
scanf("%d,%s,%f",&stu->num,&stu->name,&stu->score);
}
}
注:内容来源于谭浩强C语言第二版内容,做了小幅度改正