如何在C中创建emty链表?

时间:2016-02-17 14:54:53

标签: c list

我安装列表以及如何制作列表emty?

struct node {
   int data;
  struct node *next;
}

1 个答案:

答案 0 :(得分:1)

空列表中没有节点:

struct node *list = NULL;

如果要将节点添加到列表末尾:

void addNode(struct node **list, int value)
{
    struct node *newnode = malloc(sizeof(struct node));
    if (newnode == NULL) {
        perror("malloc failed");
        exit(1);
    } 
    newnode->data = value;
    newnode->next = NULL;
    if (*list == NULL) {
        *list = newnode;
    } else {
        struct node *temp = *list;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newnode;
    }
}

....

addNode(&list, 1);
addNode(&list, 2);
addNode(&list, 3);