C語言單鏈表-尾插法

#include<stdio.h>
#include<stdlib.h>

struct Node{
    int value;
    struct Node *next;
};

int add(struct Node **head , int val)
{
    struct Node *no = (struct Node *)malloc(sizeof(struct Node));
    no -> value = val;
    no -> next = NULL;
    if(*head == NULL)
    {
        *head = no;
    }else{
        struct Node *N_tmp = (struct Node *)malloc(sizeof(struct Node));
        N_tmp = *head;
        while(N_tmp -> next != NULL)
        {
            N_tmp = N_tmp->next;
        }
        N_tmp -> next = no;
    }
    return 0;
}

int main()
{
    struct Node *head = NULL;
    add(&head,1);
    add(&head,2);
    add(&head,3);
    add(&head,4);
    
    while(head->next != NULL)
    {
        printf("%d\n",head->value);
        head = head->next;
    }
    printf("%d\n",head->value);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章