#include <*stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)*
struct student
{
long num;
float score;
struct student *next;
};
//首先定义了一个结构体;
struct student *create() //创造一个输入信息的函数体
{
struct student *p1,*p2,*head;
//申明结构体指针变量;
int num;
float score;
int n = 0;
head = NULL;
p1 = p2 =(struct student *)malloc(LEN);
//输入常量信息,并且想要后面修改这些常量,必须申请动态内存,使用malloc来申请动态内存;printf("please input num and score.\n");
scanf("%d,%f",&p1->num,&p1->score);
while(p1->num != 0)//用0来控制结束;
{
n++;
if(n == 1)
head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct student*)malloc(sizeof(struct student));
//每次输入下一组信息时,再次给malloc申请动态内存,此时的p1和前一个p1不一样;
printf("please input num and score.\n");
scanf("%d,%f",&p1->num,&p1->score);
}p2->next = NULL;
return head;
}
void printflist(struct student *head) //打印链表,将内容打印,即“查”;
{
struct student *p;
p=head;
if(head != NULL)
{
do{
printf(“num = %d score = %f\n”,p -> num,p -> score);
p = p -> next;
}while(p != NULL);
}
}
/*while(p != NULL)
* {
printf(“num = %d,score = %f\n”,p -> num, p -> score);
p = p -> next;
* }*/
struct student *delete(struct student *head,int num) //删除函数;
{
printf(“delete.\n”);
struct student *p1,*p2;
if(head == NULL)
{
printf(“The List is NULL\n”);
}
else
{
p1 = head;
while(p1 -> next != NULL && p1 -> num != num)
{
p2 = p1;
p1 = p1 -> next;
}
if(p1 -> num == num)
{
if(p1 == head)
head =p1 -> next;
else
p2 -> next = p1 -> next; //这里是删除其实并没有删除节点,而是跳过了这个节点;
}
else
printf(“Can not find list num.\n”);
}
return head;
}
struct student *change(struct student *head,int index,int num,float score)
{
printf(“change.\n”);
struct student *p;
if(head == NULL)
{
printf(“The List is NULL.\n”);
}
else
{
p = head;
while(p -> next != NULL && p -> num != index)
{
p = p -> next;
}
if(p -> num == index)
{
p ->num = num;
p ->score =score;
}
else
printf(“Can not fine list index.\n”);
}
return head;
}
struct student *add(struct student *head,int index,int num,float score)
{
printf(“add.\n”);
struct student *p1,*p2,*p3;
if(head == NULL)
{
printf(“The List is NULL.\n”);
}
else
{
p1 = p2 = head;
while(p1 -> next != NULL && p1 -> num != index)
{
p1 = p1 -> next;
p2 = p1;
}
if(p1 -> num ==index)
{
p3 = (struct student *)malloc(LEN);
p3 -> num = num;
p3 -> score = score;
if(p2 -> next == NULL)
{
p2 -> next = p3;
p3 -> next = NULL;
}
else
{
p3 -> next = p2 -> next;
p2 -> next = p3;
}
}
else
printf(“Can not find list index.\n”);
return head;
}
}
int main()
{
struct student *head;
head = create();
printflist(head);
delete(head,3);
printflist(head);
change(head,2,5,25);
printflist(head);
add(head,3,3,35);
printflist(head);
return 0;
}
【C语言学历历程(十三)结构体与链表结合编写“增删改查”】这个是一个简单的增删改查的链表与结构体程序,作为新手来学习链表还是非常好的;
推荐阅读
- C语言学习|第十一届蓝桥杯省赛 大学B组 C/C++ 第一场
- 【C】题目|【C语言】题集 of ⑥
- 单片机|自学单片机好找工作吗(会单片机能找什么工作?)
- 单片机|keil把源代码生成lib的方法
- c语言|一文搞懂栈(stack)、堆(heap)、单片机裸机内存管理malloc
- c语言|C语言初期学习遇到的特殊点 【三子棋详解】【初学者福音,详细总结,复习能手】
- 笔记|C语言数据结构——二叉树的顺序存储和二叉树的遍历
- 个人理解|【C语言基础之类型转换】
- c语言|【C语言】自定义类型 结构体 枚举 联合
- 学习分享|【C语言函数基础】