首页 > 关于链表创建的一个疑问

关于链表创建的一个疑问

如下代码,我的思路是init函数创建一个节点和一个指向节点的指针(堆上分配),然后返回这个指针作为头指针,add2tail就是向链表的尾部添加一个节点,但是为什么没有正确运行

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

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


struct node *  init(int data){
    struct node * head = (struct node *)malloc(sizeof(struct node *));
    struct node *  n = (struct node * )malloc(sizeof(struct node));
    n->data = data;
    n->next = NULL;
    head = n;
    return head;
}

void add2tail(struct node *  list, int data){
    struct node *  n = list;
    while (n != NULL){
        n = n->next;
    }
    struct node *  newnode = (struct node * )malloc(sizeof(struct node));
    n = newnode;
    newnode->data = data;
    newnode->next = NULL;
    return;
}

void print(struct node *  list){
    struct node *  n = list;
    while (n != NULL){
        printf("%d ", n->data);
        n = n->next;
    }
    printf("\n");
    return;
}

int main(void){
    struct node *  head = init(123);
    print(head);
    add2tail(head, 7);
    print(head);
    system("pause");
    return 0;
}

修改两处

while(  n->next  !=  null  )

n->next  =  newnode;
【热门文章】
【热门文章】