首页 > 代码库 > 链表基本操作
链表基本操作
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct student *Liststu; 4 struct student { 5 int age; 6 Liststu next; 7 }; 8 Liststu inset(Liststu stu, int age); 9 void print(Liststu stu); 10 Liststu Swap_Data_Sort(Liststu stu); 11 Liststu Swap_List_Sort(Liststu stu); 12 Liststu swap(Liststu stu); 13 int main() 14 { 15 Liststu stu; 16 stu = NULL; 17 stu = inset(stu, 19); 18 stu = inset(stu, 26); 19 stu = inset(stu, 15); 20 stu = inset(stu, 18); 21 stu = inset(stu, 25); 22 stu = inset(stu, 21); 23 stu = inset(stu, 20); 24 stu = Swap_List_Sort(stu); 25 print(stu); 26 return 0; 27 } 28 Liststu inset(Liststu stu, int age) //插入数据(尾插法) 29 { 30 Liststu temp, temp1; 31 temp = (Liststu)malloc(sizeof(*temp)); 32 temp1 = (Liststu)malloc(sizeof(*temp1)); 33 if(temp == NULL || temp1 == NULL) { 34 printf("创建失败!"); 35 exit(1); 36 } 37 temp1 = stu; 38 temp->age = age; 39 if(temp1) { 40 while(temp1->next != NULL) { 41 temp1 = temp1->next; 42 } 43 temp1->next = temp; 44 temp->next = NULL; 45 } 46 else { 47 temp->next = NULL; 48 stu = temp; 49 } 50 return stu; 51 } 52 void print(Liststu stu) //打印链表 53 { 54 for(; stu; stu = stu->next) { 55 printf("%d\n", stu->age); 56 } 57 } 58 Liststu Swap_Data_Sort(Liststu stu) //链表排序(数据交换) 59 { 60 int temp; 61 Liststu p1, p2; 62 p1 = stu; 63 while(p1) { 64 for(p2 = p1->next; p2; p2 = p2->next) { 65 if(p1->age > p2->age) { 66 temp = p1->age; 67 p1->age = p2->age; 68 p2->age = temp; 69 } 70 } 71 p1 = p1->next; 72 } 73 return stu; 74 } 75 Liststu Swap_List_Sort(Liststu stu) 76 { 77 Liststu p1, p2, temp1, temp2; 78 p1 = stu; 79 while(p1) { 80 for(p2 = p1->next; p2; p2 = p2->next) { 81 if(p1->age > p2->age) { 82 temp1 = p1; 83 temp2 = p2; 84 p2->next = temp1->next; 85 p2 = p1; 86 p1->next = temp2->next; 87 p1 = temp2; 88 } 89 } 90 p1 = p1->next; 91 } 92 return stu; 93 } 94 Liststu swap(Liststu stu) //交换两个节点 95 { 96 Liststu p1, p2, temp, prep1, prep2; 97 p1 = stu->next; 98 prep1 = stu; 99 prep2 = p1->next; 100 p2 = prep2->next; 101 temp = p2->next; 102 prep1->next = p2; 103 prep2->next = p1; 104 p2->next = prep2; 105 p1->next = temp; 106 return stu; 107 }
链表基本操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。