单向链表及其相关基本操作【C语言】

#include 
#include 
#include 
typedef struct List{
    int data;
    struct List *next;
}Node;


Node *initList(){
    Node *p = (Node*)malloc(sizeof(Node));
    p->next = NULL;
    return p;
}
/*
    直接传地址初始化
    void initList(Node **q){
        (*q) = (Node*)malloc(sizeof(Node));
        (*q)->next = NULL;
    }

*/

void addNode(Node **L, int n){
    Node *p = *L;
    while(p->next != NULL){
        p = p->next;
    }
    Node *temp = (Node*)malloc(sizeof(Node));
    temp->data = n;
    temp->next = NULL;
    p->next = temp;
}

void deleteNode(Node **L,int n){
    Node *p = *L;
    while(p->next != NULL){
        
        if(p->next->data == n){
            Node *temp = p->next->next; //要暂时记录一下要链接的节点,否则释放节点后无法访问
            free(p->next);
            p->next = temp;
            break;
        }
        p = p->next;  //通过8即可访问9
    }
}

void showList(Node *L){
    Node *p = L;
    while(p->next != NULL){
        p = p->next;
        printf("%d ",p->data);
    }
}

int main() {
    Node* L = NULL;
    L = initList();
    addNode(&L,3);
    addNode(&L,4);
    addNode(&L,7);
    addNode(&L,8);
    addNode(&L,9);
    showList(L);
    deleteNode(&L,3);
    printf("\n");
    showList(L);
    return 0;
}

 

你可能感兴趣的:(数据结构)