博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C的动态链表建立
阅读量:4579 次
发布时间:2019-06-09

本文共 2489 字,大约阅读时间需要 8 分钟。

运用到的函数为:

动态内存分配函数malloc()              比如:char *name=(char *)malloc(20);  相当与c++的new关键字

动态内存释放函数free()                 比如:free(name); 相当于c++的delete关键字

计算数据空间的字节数sizeof()         比如:p1 = (struct A*)malloc(sizeof(struct A));

这个链表很多地方没有加判断,判断字符的输入造成的死循环等等,也就大致的学习一下C的动态建立与C++的区别而已。

 

#include 
#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;}

  

转载于:https://www.cnblogs.com/BlackCat86/p/4439039.html

你可能感兴趣的文章