美文网首页
C-Linked-list

C-Linked-list

作者: 郑铭皓 | 来源:发表于2016-10-20 21:17 被阅读0次

    //Linked-list#include#includetypedef struct _node{

    int value;

    struct _node *next;  //point to the next node;

    } Node;

    typedef struct List{

    Node *head;

    // Node *tail;

    }List;

    void add(List *plist, int number);

    void print(List *plist);

    void foundnum(List *plist, int number);

    void delfoundednum(List *plist, int number);

    int main(int arge, char const *argv[])

    {

    // Node * head = NULL;

    List list;

    list.head = NULL;

    int number;

    do{

    scanf("%d",&number);

    if(number != -1 ){

    add(&list, number);

    }

    } while ( number != -1 );

    print(&list);

    scanf("%d",&number);

    foundnum(&list, number);

    delfoundednum(&list, number);

    print(&list);

    return 0;

    }

    // another choice:

    // Node *add(Node **phead, int number)

    // int main(){...head = add(&head, number);...}

    void add(List *plist, int number)

    {

    // add to linked-list;

    Node *p=(Node*)malloc(sizeof(Node));

    p->value = number;

    p->next = NULL;

    //Finde the last;

    Node *last = plist->head;

    if( last ){

    while( last->next ){

    last = last->next;  // plist->head = plist->head->next;

    } // attach;

    last->next = p;  // plist->head->next = p;

    }else {

    plist->head=p;

    }

    // printf("o");

    }

    void print(List *plist)

    {

    Node *p;

    for (p = plist->head; p; p = p->next){

    printf("%d\t",p->value);

    }

    printf("\n");

    }

    void foundnum(List *plist, int number)

    {

    Node *p;

    int isfound = 0;

    for(p = plist->head; p; p = p->next){

    if(p->value == number){

    printf("isfound\n");

    isfound = 1;

    break;

    }

    }

    if(!isfound)printf("isnotfound\n");

    }

    void delfoundednum(List *plist, int number)

    {

    Node *p,*q;

    int isfound = 0;

    for(q = NULL, p = plist->head; p; q = p, p = p->next){

    if(p->value == number){

    if( q ){

    q->next = p->next;

    }else{

    plist->head=p->next;

    }    // q = p; p = p->next; q->next = p->next; free(p);

    free(p);

    break;

    }

    // Any pointer at the left of ->must be check whether it is NULL;

    }

    // delete list;

    // for(p=plist->head; p; p=q){

    // q=p->next;

    // free(p);

    // }

    }

    相关文章

      网友评论

          本文标题:C-Linked-list

          本文链接:https://www.haomeiwen.com/subject/prcquttx.html