C的动态链表建立
运用到的函数为:
动态内存分配函数malloc() 比如:char *name=(char *)malloc(20); 相当与c++的new关键字
动态内存释放函数free() 比如:free(name); 相当于c++的delete关键字
计算数据空间的字节数sizeof() 比如:p1 = (struct A*)malloc(sizeof(struct A));
这个链表很多地方没有加判断,判断字符的输入造成的死循环等等,也就大致的学习一下C的动态建立与C++的区别而已。
#include <stdio.h> #define LENG sizeof(struct A) struct A { int num; char name[20]; struct A *next; }; struct A *head = NULL; //头指针 struct A* lb(); //建立链表函数 void cha(struct A *head); //查询函数 struct A* charu(struct A* head); //插入函数 struct A* Delete(struct A*head,int x); //删除函数 int main() { int y; int x = 0; while (1) { printf("(1)建立链表(2)查询链表(3)插入(4)删除(5)退出\n"); scanf_s("%d", &y); switch (y) { case 1:head = lb(); break; case 2:cha(head); break; case 3:head = charu(head); break; case 4: if (head == NULL) { printf("您的链表为空\n"); break; } printf("请输入要删除的编号:"); scanf_s("%d", &x); head = Delete(head,x); break; case 5:break; default: printf("输入错误请重新输入\n"); continue; } if (y == 5)break; } system("pause"); return 0; } struct A* lb() { struct A *p1=NULL, *p2=NULL; int a, b, c; p1 = p2 = (struct A*)malloc(LENG); head = p1; printf("请输入编号:"); scanf_s("%d", &p1->num); printf("请输入姓名:"); scanf_s("%s", p1->name, 20); while (1) { p1 = (struct A*)malloc(LENG); printf("请输入编号0为结束:"); scanf_s("%d", &a); if (a == 0) { free(p1); p2->next = NULL; break; } p1->num = a; printf("请输入姓名:"); scanf_s("%s", p1->name, 20); p2->next = p1; p2 = p1; } return head; } void cha(struct A *head) { while (1) { if (head == NULL) { printf("您的链表为空\n"); break; } printf("%d\t%s\n", head->num, head->name); if (head->next == NULL) { break; } head = head->next; } } struct A* charu(struct A* head) { struct A *p1, *p2, *p3; p1 = (struct A*)malloc(sizeof(struct A)); p2 = head; printf("请输入编号:"); scanf_s("%d", &p1->num); printf("请输入姓名:"); scanf_s("%s", p1->name, 20); if (head->num > p1->num) { p1->next = head; return p1; } p3 = head; while (1) { if (p1->num < head->num) { p1->next = head; p3->next = p1; break; } else { p3 = head; if (head->next == NULL) { head->next = p1; p1->next = NULL; break; } head = head->next; } } return p2; } struct A* Delete(struct A*head,int x) { struct A *p1,*p2; p1 = p2 = head; if (head->num == x) { p1 = head; head = head->next; free(p1); return head; } while (1) { if (head->num == x) { p1->next = head->next; break; } else { p1 = head; head = head->next; } } return p2; }