关于链表创建的一个疑问

新手上路,请多包涵

如下代码,我的思路是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;
}
阅读 2.4k
1 个回答
修改两处

while(  n->next  !=  null  )

n->next  =  newnode;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题