mylinklist

来源:互联网 发布:滨州行知中学招生电话 编辑:程序博客网 时间:2024/06/14 18:45
#include <stdio.h>#include <string.h>#include <stdlib.h>#define NAME_MAX 30typedef struct student_node *S_P;typedef struct student_node{int id;char name[NAME_MAX];float score;struct student_node *next;}S_T;//创建节点S_P mk_node(int id, char *name, float score){S_P p = malloc(sizeof(S_T));if(p != NULL){p->id = id;strcpy(p->name,name); //字符串p->score = score;p->next = NULL;}return p;}//从head插入S_P insert_head(S_P head, int id, char *name, float score){S_P newp = mk_node(id, name, score);if(!head || !newp){if(!head){head = newp;}return head;}newp->next = head;head = newp;return head;}//从tail插入S_P insert_tail(S_P head, int id, char *name, float score){S_P newp = mk_node(id, name, score);S_P tail;if(!head || !newp){if(!head){head = newp;}return head;}for(tail = head; tail->next; tail = tail->next);//tail存放是是尾节点tail->next = newp;return head;}//按升序插入nodeS_P insert_sort_node(S_P head, int id, char *name, float score){S_P newp = mk_node(id, name, score);S_P pre, cur;//判断head newp node是否创建成功if(!head || !newp){ if(!head){head = newp;}return head;}for(pre = cur = head; cur && cur->score < score; pre = cur, cur = cur->next);if(cur == head){newp->next = head;head = newp;}else{newp->next = cur;pre->next = newp;}return head;}//打印linklistvoid disp_linklist(S_P head){S_P cur;for(cur = head; cur; cur = cur->next){printf("%d\t%s\t%.2f\n", cur->id, cur->name, cur->score);}}void delete_linklist(S_P head){S_P cur, next;#if 1for(cur = head; cur; cur = next){next = cur->next;free(cur);}#endif#if 0cur = head;while(cur != NULL){next = cur->next;free(cur);cur = next;}#endif}S_P delete_node(S_P *headp, float key){S_P del, pre, cur;//没有head节点的情况if(*headp == NULL)return NULL;//删除的节点恰好是头结点if( (*headp)->score == key ){del = *headp;*headp = (*headp)->next;del->next = NULL;return del;}for( pre = *headp, cur = (*headp)->next; cur; pre = pre->next, cur = cur->next){if(cur->score == key ){del = cur;cur = cur->next;del->next = NULL;pre->next = cur;return del;}}return NULL;}int main(void){int id;char name[NAME_MAX];float score;S_P head = NULL, del;while(1){scanf("%d %s %f", &id, name, &score);getchar();if(id == 0 )break;//head = insert_sort_node(head, id, name, score);//要有返回值//head = insert_head(head, id, name, score);head = insert_tail(head, id, name,score);}printf("---------------\n");disp_linklist(head);while( (del = delete_node(&head, 3)) ){printf("del:%d %s %f\n", del->id, del->name, del->score);free(del);}printf("---------------\n");disp_linklist(head);delete_linklist(head);return 0;}/*akaedu@akaedu-G41MT-D3:~/lin/809$ ./mylinklist 1 adad  885 linbo 864 adav 30 0 0---------------1adad88.005linbo86.004adav3.00del:4 adav 3.000000---------------1adad88.005linbo86.00*/

0 0