C语言学历历程(十三)结构体与链表结合编写“增删改查”

#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语言学历历程(十三)结构体与链表结合编写“增删改查”】这个是一个简单的增删改查的链表与结构体程序,作为新手来学习链表还是非常好的;

    推荐阅读