【问题标题】:C linked list to Display contentsC链表显示内容
【发布时间】:2016-10-21 04:55:25
【问题描述】:

代码中有没有遗漏的部分?

我正在创建一个非空链接 list 并显示链表的内容。我哪里弄错了?

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

struct node_int
{
    void *data;
    node next;
};

typedef struct node_int *node;
typedef struct list_int { node first; } *list;

void init_list(list *lp, void *o)
{
    *lp = (list) malloc(sizeof(struct list_int));
    (*lp)->first = NULL;
    (*lp)->first->data = o;
    (*lp)->first->next = NULL;
}

void print(list ell, void (*print_data)(void *d))
{
    list c;
    c = ell;
    while (c!NULL)
    {
        print_data(c->data);
        c = ell;
    }
}

【问题讨论】:

  • (*lp)-&gt;first = NULL; (*lp)-&gt;first-&gt;data = o; : NULL-&gt;data = o; !!
  • print_data(c-&gt;data); c = ell; 不更新c
  • 能否请您发布可编译的代码,或者更好地说明整个程序以及它在哪里出现问题,以便我们知道在哪里寻找问题?

标签: c struct linked-list


【解决方案1】:

您的代码存在一些问题。

首先想说的是,我觉得给typedef一个指针的风格不好。如果你这样做,你至少应该使用一个清楚地表明类型是指针的名称。像listnode 这样的名字会让其他人想到不是指针的东西。

下面是一些代码,展示了没有 typedef 指针的情况。

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

struct node_int
{
    void *data;
    struct node_int* next;
};

typedef struct node_int node;
typedef struct list_int { node* first; } list;


void init_list(list** lp, void *o)
{
    // Allocate the list
    *lp = malloc(sizeof(list));
    if (*lp == NULL) return;

    // Allocate the first node
    (*lp)->first = malloc(sizeof(node));
    if ((*lp)->first == NULL)
    {
        free(*lp);
        *lp = NULL;
        return;
    }

    // Initialize first element
    (*lp)->first->data = o;
    (*lp)->first->next = NULL;
}

void print(list* ell, void (*print_data)(void *d))
{
    if (ell == NULL) return;

    node* p = ell->first;
    while (p != NULL)
    {
        print_data(p->data);
        p = p->next;
    }
}

void myPrint(void* d)
{
  int* p = (int*)d;
  printf("%d\n", *p);
}

void free_list(list* ell)
{
    // Add code here ...
}

int main(void)
{
    int a = 1;
    list* myList;
    init_list(&myList, &a);
    if (myList == NULL) return 0;

    // Use the list.....
    print(myList, myPrint);

    free_list(myList);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多