1 #include<stdio.h> 2 #include<stdlib.h> 3 4 struct chain 5 { 6 int num; 7 float score; 8 struct chain *next; 9 }; 10 11 //创建新链表 12 struct chain *create() 13 { 14 struct chain *head; 15 //申请新节点空间 16 head = (struct chain *)malloc(sizeof(struct chain)); 17 if(head == NULL) 18 { 19 printf("申请节点失败 "); 20 return NULL; 21 } 22 return head; 23 } 24 25 //加入新的节点 26 struct chain *insert(struct chain *head,struct chain *s) 27 { 28 struct chain *p=head; 29 //如果链表循环并且新节点的分数大于下一个节点的分数 30 while((p->next != NULL) && (s->score > p->next->score)) 31 { 32 p=p->next; 33 } 34 //如果链表循环到结尾 35 if(p->next == NULL) 36 { 37 p->next = s; 38 s->next = NULL; 39 } 40 //如果新的节点的分数大于下一个节点的分数 41 else 42 { 43 p->next = s; 44 s->next = p->next; 45 } 46 return head; 47 } 48 49 //查找符号条件的节点 50 struct chain *search(struct chain *head) 51 { 52 int num; 53 struct chain *p = head; 54 printf("请输入要查找的学生的学号: "); 55 scanf("%d",&num); 56 57 //链表循环并且链表中的学号不等于要查找的学号 58 while((p->next != NULL) && (p->num != num)) 59 { 60 p=p->next; 61 } 62 63 //链表循环到结尾 64 if(p->next == NULL) 65 { 66 printf("查找学号失败,没有这个学号 "); 67 return NULL; 68 } 69 //链表中的学号等于要查找的学号 70 else 71 { 72 printf("找到符号条件的学号num=%d %f",p->num,p->score); 73 return p; 74 } 75 } 76 77 //对链表进遍历输出 78 void printf_list(struct chain *head) 79 { 80 struct chain *p = head; 81 printf("链表如下: "); 82 83 while(p->next != NULL) 84 { 85 printf("学生的学号%d,成绩%f",p->num,p->score); 86 p=p->next; 87 } 88 } 89 90 //释放链表 91 void free_list(struct chain *head) 92 { 93 struct chain *p = head; 94 95 while(p->next != NULL) 96 { 97 head = head->next; 98 free(p); 99 p=head; 100 } 101 printf("释入链表成功 "); 102 } 103 104 //删除链表符合条件的节点 105 struct chain *delete_list(struct chain *head,int num) 106 { 107 struct chain *p = head; 108 struct chain *q = head->next; 109 110 while((q != NULL) && (q->num != num)) 111 { 112 p=q; 113 q=q->next; 114 } 115 116 if(q == NULL) 117 { 118 printf("删除失败,没有找到符合条件的节点 "); 119 return NULL; 120 } 121 else 122 { 123 p->next = q->next; 124 free(q); 125 printf("删除节点成功 "); 126 } 127 return head; 128 } 129 130 int main() 131 { 132 struct chain *p,*head; 133 int num; 134 int c; 135 float score; 136 printf("有头节点的链表操作程序: "); 137 head = create(); 138 139 while(1) 140 { 141 printf("I:插入节点(自动升序) P:输出链表 S:查找节点 D:删除节点 142 E:释入链表并退出程序 "); 143 c = getchar(); 144 switch(c) 145 { 146 case'I': 147 printf("请分别输入要插入学生的学号和成绩 "); 148 scanf("%d%f",&num,&score); 149 p = (struct chain *)malloc(sizeof(struct chain)); 150 if(p == NULL) 151 { 152 printf("申请节点失败 "); 153 exit(0); 154 } 155 p->num = num; 156 p->score = score; 157 insert(head,p); 158 printf("插入成功 "); 159 break; 160 case'P': 161 printf_list(head); 162 break; 163 case'S': 164 search(head); 165 break; 166 case'D': 167 printf("请输入要删除学生的学生号: "); 168 scanf("%d",&num); 169 delete_list(head,num); 170 break; 171 case'E': 172 free_list(head); 173 exit(0); 174 } 175 } 176 return 0; 177 }