single linkList (draft)

来源:互联网 发布:淘宝正品coach代购推荐 编辑:程序博客网 时间:2024/05/16 01:27
//All Rights Reserved #include <stdio.h> #include <stdlib.h> struct node{     int age;     struct node *next; }; void printList(node *N); node *insertNode(node *, int); node *deleteNode(node *, int); int getListSize(node *); int main() {     printf("******* welcome to my c world *******\n\n");     printf("****** nodeA->nodeB->nodeC->NULL ******\n");     printf("******   1  ->  2  ->  3  ->NULL ******\n\n");     //create initial Link     struct node *link;link=(node *)malloc(sizeof(node));     link->next = NULL;     int menu, age, location;     while (1)     {         printf("********** print menu **********\n");         printf("please choose an operation: \n");         printf("1: insert a node from head\n");         printf("2: delete a node\n");         printf("0: exit!\n");         printf("********** print menu **********\n\n");         scanf("%d", &menu);         if (menu==1)         {             printf("insert a date\n");             printf("please input the age: ");             scanf("%d", &age);             link = insertNode(link, age);             printList(link);         }         else if (menu==2)         {             printf("delete a date\n");             printf("please input the location: ");             scanf("%d", &location);             link = deleteNode(link, location);             printList(link);         }         else if (menu==0)             break;         else             printf("error input!\n");     }     return 0; } // a->b->c->NULL node *insertNode(node *N, int a) {     node *M = (node *)malloc(sizeof(node));     M->age = a;     M->next = N;     return M; } int getListSize(node *N){     int i=0;     while (N->next != NULL)     {         i++;         N = N->next;     }     return i; } node *deleteNode(node *N, int l) {     node *M, *T;     M = N;     int i, s = getListSize(N);     if ( l<1 || l>s )     {         printf("location out of list size(1, %d), do nothing\n", s);         return N;     }     if (l == 1)     {         printf("delete head\n");         M = M->next;         free(N);     }     else if (l == s)     {         printf("delete tail\n");         while (M->next->next != NULL)             M = M->next;free(M->next);         M->next = NULL;M = N;     }     else{         for (i=0; i<(l-2); i++)             M = M->next;         T = M->next->next;         free(M->next);         M->next = T;     }     return M; } // null tree not check void printList(node *N){     printf("\n********** print list **********\n");     node *M;     M = N;     do     {         printf("%d ", M->age);         M = M->next;     }while (M->next != NULL);     printf("\n********** print list **********\n\n"); }