简体   繁体   English

如何显示在链接列表中创建的数据?

[英]How can I display the data I created in a linked list?

I think there is something wrong with my create. 我认为我的创作存在问题。

void add(N *p) {
    N *current, *start;
    current = malloc(sizeof(p));
    scanf("%d", &current->data);
    current->next = NULL;

    if (p == NULL) {
        p = current;
        start = current;
    } else {
        start->next = current;
        start = current;
    }
}

I think that my display() is correct. 我认为我的display()是正确的。

void display(N *p) {
    N *current;
    current = p;
    while (current != NULL) {
        printf("\n%d", current->data);
        current = current->next;
    }
}

Your malloc(sizeof(p)) only returns enough space for a pointer . 您的malloc(sizeof(p))仅返回足够的空间用于指针 You instead want malloc(sizeof(N)) . 相反,您需要malloc(sizeof(N))

Also, you need to return the new value of p instead of throwing it away at the end of add() . 另外,您需要返回p的新值,而不是将其扔在add()的末尾。 (Your start has a similar issue; pick one to be the head of your linked list.) (您的start有一个类似的问题;请选择一个作为链接列表的头。)

There are problems: 有问题:

  • function add() does not allocate the correct amount of memory. 函数add()无法分配正确的内存量。 Use this method: 使用此方法:

     current = malloc(sizeof(*current)); 
  • The way you are inserting the newly allocated object into the list does not work: you modify p , which is an argument with local scope, and you set start which also has local scope. 将新分配的对象插入列表的方式无效:您修改p ,它是具有局部范围的参数,并且设置了start也具有局部范围。 No side effect is performed on the N pointer is the callers scope. 在调用方范围内,对N指针没有任何副作用。

  • Your display function is correct, but I would favor adding the newline at the end of the output instead of at the beginning. 您的display功能是正确的,但我希望在输出的末尾而不是在开头添加换行符。

Here is an updated version with a better API: 这是具有更好API的更新版本:

int add(N **headp) {
    N *current = calloc(sizeof(*current));
    if (current == NULL) {
        fprintf(stderr, "cannot allocate memory for new object\n");
        return -1;
    }
    if (scanf("%d", &current->data) != 1) {
        fprintf(stderr, "cannot read value for new object\n");
        return -2;
    }
    current->next = *headp;
    *headp = current;
    return 0;
}

void display(const N *list) {
    for (const N *p = list; p != NULL; p = p->next) { 
        printf("%d\n", p->data);
    }
}

The add function is used this way from the caller: 调用者以这种方式使用add函数:

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

typedef struct N {
    int data;
    struct N *next;
} N;

int main(void) {
    N *list = NULL;

    for (i = 0; i < 10; i++) {
        if (add(&list))
            break;
    }
    display(list);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM