簡單的單向連結串列

weixin_51408986發表於2020-11-27
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
    int value;
    struct _node *next;
}Node;
typedef struct _list {  //為將來的升級提高了無限的可能
    Node* head;
//    Node* tail;
}List;
void add(List *plist, int number);
void print(List *plist);
void delete(List* plist,int dl);
void all_delete(List* plist);

int main()
{                                   //head已經是指標
//    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);
    int dl;
    scanf("%d",&dl);
    delete(&list,dl);
    print(&list);
    all_delete(&list);
    //
    return 0;
}
void add(List* plist, int number)//傳入指標的指標,使我們能夠對指標的值進行修改
{
    //add to linked-list
    Node *p = (Node*)malloc(sizeof(Node));
    p->value = number;
    p->next = NULL;
    //find the last
    Node *last = plist->head;
    if( last != NULL ) {
        while(last->next != NULL) {
            last = last->next;
        }
        //attach
        last->next = p;
    }else plist->head = p;
}
void print(List *plist)
{
    Node* p;
    for( p=plist->head; p !=NULL ;p=p->next ) {
        printf("%d\t",p->value);
    }

}
void delete(List* plist,int dl)
{
    Node *p;
    Node *q;
    for( q=NULL,p=plist->head; p ;q=p,p=p->next ) {
        if( p->value == dl ) {
            if( q ) {
                q->next = p->next;
            }else {
                plist->head = p->next;
            }
            free(p);
            break;
        }
    }
}
void all_delete(List* plist)
{
    Node *p,*q;
    for( p = plist->head; p ; p=q ) {
        q = p->next;
        free(p);
    }
}

相關文章