本文共 1923 字,大约阅读时间需要 6 分钟。
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- //定义学生的结构体
- typedef struct stu
- {
- int id;
- char name[20];
- struct stu * next;
- }stu;
- //该函数是创建学生信息
- stu *Create_chain()
- {
- stu* head = NULL;
- stu* p1 = NULL;
- stu* p2 = NULL;
- p1 = (stu*)malloc(1*sizeof(stu));
- printf("please input a stu infor\n");
- scanf("%d%s", &(p1->id), p1->name);
- p2 = head = p1;
- while(p1->id != 0)
- {
- p1 = (stu*)malloc(1*sizeof(stu));
- printf("please input a stu infor\n");
- scanf("%d%s", &(p1->id), p1->name);
-
- p2->next = p1;
- p2 = p1;
- }
- p2->next = NULL;
- return head;
- }
- //该函数是打印学生信息
- void Print_chain(stu * head)
- {
- stu *p;
- p = head;
- while(p->next != NULL)
- {
- printf("%-12d%-12s\n",p->id, p->name);
- p = p->next;
- }
- }
- //该函数是插入学生信息
- void Insert_info(stu* head, stu* temp)
- {
- stu* p1 = NULL;
- stu* p2 = NULL;
- p1 = head;
- if(head == NULL)
- {
- head = temp;
- temp->next = NULL;
- }
- else
- {
- while((p1->next != NULL) && (p1->id<temp->id))
- {
- p2 = p1;
- p1 = p1->next;
- }
- if(p1->id > temp->id)
- {
- p2->next = temp;
- temp->next = p1;
- }
- if (p1->next == NULL)
- {
- p1->next = temp;
- temp->next = NULL;
- }
- }
- }
- stu* Delete_info(stu* head, int id)
- {
- stu* p1 = NULL;
- stu* p2 = NULL;
- p1 = head;
-
- if (head == NULL)
- {
- printf("not exist stu_info\n");
- return head;
- }
-
- while((p1->next != NULL)&& (p1->id != id))
- {
- p2 = p1;
- p1 = p1->next;
- }
- if (p1->id == id)
- {
- if (p1 == head)
- {
- head = p1->next;
- }
- else
- {
- p2->next = p1->next;
- }
- }
- else
- {
- printf("not find the stu\n ");
- }
- return head;
- }
- void Free_chain(stu* head)
- {
- stu *p;
- p = head;
- while(p->next != NULL)
- {
- free(p);
- p = p->next;
- }
- }
- int main()
- {
- int id ;
- stu* head;
- stu* tmp = (stu*)malloc(1*sizeof(stu));
- head = Create_chain();
- Print_chain(head);
- puts("please input stu info\n");
- scanf("%d%s", &tmp->id, tmp->name);
- Insert_info(head, tmp);
- Print_chain(head);
- printf("please input the id you want delete\n");
- scanf("%d\n", &id);
- head = Delete_info(head, id);
- Print_chain(head);
- Free_chain(head);
- return 0;
- }
转载于:https://www.cnblogs.com/wxishang/p/3440706.html