C语言--链表基础模板

1.建立结构体

1 struct ST
2 {
3     int num;///学号
4     int score;///成绩
5     struct ST*next;
6 };///结构体

2.空链表的创建

 1 struct ST creatNullList(struct ST *head)///创建空链表
 2 {
 3 
 4     head = (struct ST*)= malloc(sizeof(struct ST));
 5     if(head!=NULL)
 6     {
 7         head->next=NULL;
 8     }
 9     else
10     {
11         printf("Out of space!
");
12     }
13     return head;
14 };

3.添加结点

 1 struct ST append(struct ST *head)///向链表中追加结点
 2 {
 3     struct ST *p,*pnew;
 4     pnew=(struct ST*)=malloc(sizeof(struct ST));
 5     /*pnew->n=0;
 6     pnew->score=s;//给追加的元素赋值*/
 7     p=head;///p先指向头结点
 8     while(p->next!=NULL)
 9     {
10         p=p->next;
11     }///遍历整个链表直到指向链尾时退出循环
12     p->next=pnew;///将新结点连入链表
13     pnew->next=NULL;///新结点成为链尾
14     return head;
15 }

4.删除结点

 1 struct ST Delete(struct ST *head)///删除链表中的结点
 2 {
 3     int num;
 4     struct ST *p,*q;
 5     p=head;
 6     scanf("%d",&number);///请输入要删除的学生的学号
 7     while((p->next!=NULL)&&(number!=p->n)
 8     {
 9         q=p;///q作为中间变量,存储要删除的结点之前的一个结点
10         p=p->next;///p存储的是要删除的结点
11     }
12     q->next=p-next;///将要删除的结点排除到链表之外
13     return head;
14 }

5.插入结点

 1 struct ST Insert(struct ST *head,struct ST *p)///在结点p之后插入一个新的结点
 2 {
 3     struct ST *pnew;
 4     pnew=(struct ST*)=malloc(sizeof(struct ST));
 5     /*pnew->num=n;
 6     pnew->score=score;///插入新结点的赋值*/
 7     pnew->next=p->next;
 8     p-next=pnew;
 9     return head;
10 };

应用

原文地址:https://www.cnblogs.com/wkfvawl/p/9301779.html