c - 关于链表创建的一个疑问

查看:113
本文介绍了c - 关于链表创建的一个疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如下代码,我的思路是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;

这篇关于c - 关于链表创建的一个疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆