本链表包括功能有:
创造n个节点的链表
插入一个节点
删除一个节点
可用于制作C语言学籍管理系统,可做借鉴。
代码如下:
#include<stdio.h>
#include<stdlib.h>//malloc函数的库函数
#include<string.h>
static int s;
struct student//定义一个结构体
{
char number[20];
struct student *next;
};
struct student *create(int n)//返回值为一个结构体类型的指针,创造n个节点的链表
{
struct student *head, *p_new, *p_end;
head = NULL;
for(int i = 0;i < n;i++)//创造节点的循环
{
p_new = (struct student *)malloc(sizeof(struct student));//malloc函数返回的值是结构体类型的指针地址
if(p_new == NULL)
{
printf("动态分配储存空间失败");
break;
}
printf("请输入第%d个学生的学号:", i+1);
scanf("%s", p_new->number);
if(i == 0)
{
head = p_new;
p_end = p_new;
p_end->next = NULL;
}
else
{
p_end->next = p_new;
p_end = p_new;
p_end->next = NULL;
}
}
return head;
}
struct student *insert(struct student *head)//插入一个节点
{
struct student *p_new;
p_new = (struct student *)malloc(sizeof(struct student));
if(p_new == NULL)
{
printf("插入节点分配储存空间失败");
return NULL;
}
printf("请输入学生学号:");
scanf("%s", p_new->number);
p_new->next = head;
head = p_new;
s++;
return head;
}
struct student *del(struct student *head)//删除其中的一个节点
{
char a[20];
struct student *b, *c;
b = head;
printf("请输入该学生的学号:");
getchar();
gets(a);
for(int i = 0;i < s;i++)
{
if((strcmp(a, b->number) == 0) && i == 0)
{
b = b->next;
head = b->next;
free(b);
printf("删除成功\n");
return head;
}
else if(strcmp(a, b->number) == 0)
{
c->next = b->next;
free(b);
printf("删除成功\n");
return head;
}
c = b;
b = b->next;
}
}
int main(void)
{
printf("请输入创造几个学生信息:");
scanf("%d" , &s);
struct student *p, *i;
p = create(s);
i = p;
while(p != NULL)
{
printf("%s\n", p->number);
p = p->next;
}
i = del(i);
while(i != NULL)
{
printf("%s\n", i->number);
i = i->next;
}
return 0;
}