【问题标题】:Struct singly linked list. Why does this not work?构造单链表。为什么这不起作用?
【发布时间】:2018-03-24 07:17:40
【问题描述】:
#include <stdio.h>

struct item {
    int key;
    int data;
    struct item *next;
};

struct item *head = NULL;

int main()
{
    extern void filllist(), printall();
    filllist();
    printall();
    return(0);
}


void filllist()
{
    static struct item a, b, c, d;
    head = &a;
    a.key = 5;
    a.data = 0;
    a.next = &b;
    b.key = 20;
    b.data = 2;
    b.next = &c;
    c.next = &d;
    c.key = 22;
    c.data = 6;
    d.key = 38;
    d.data = 3;
    d.next = NULL;
}

void printall()
{
    static struct item h;
    head = &h;
    for(int i = 0; i < 5; i++) {
        printf("%d: %d\n", h.data, h.key);
        h = h.next;
    }

}

对于 printtall 函数,我收到错误“错误:从类型 'struct item *' 分配给类型 'struct item' 时不兼容的类型”。还有一种方法可以在没有固定 for 循环的情况下遍历单链表吗?我想从fillist打印出单链表。

有人可以帮助我如何让 printtall 工作吗?谢谢

【问题讨论】:

  • 您从哪里了解到staticextern 的这种用法?这是语言的非惯用用法并且容易出错。无论如何,你的问题是题外话,原因是明确的(“为什么这段代码不起作用?”)。
  • @axiac 问题之一是它不起作用,因此它与代码审查无关。在将用户重定向到 Code Review 之前,请阅读 our guide for SO migration
  • @Zeta 明白了。感谢您指出这一点。

标签: c struct


【解决方案1】:

您在此处分配一个指向结构的指针:

h = h.next;

hstruct item 类型,但h.next 是指向struct item指针,因此您不能将h 设置为等于h.next

也许你想要:

h = *h.next;

打印列表的更好方法是:

void printall(struct item* h)
{
    while (h != NULL) {
        printf("%d: %d\n", h->data, h->key);
        h = h->next;
    }
}

然后这样称呼它:

printall(head);

除此之外,您应该摆脱所有 static 变量。

例如创建一个添加单个项的函数。通常你会使用动态内存(malloc),但这里是一个没有动态内存的例子,即所有在 main 中定义的变量(并且没有静态变量):

struct item* add_to_front(struct item* h, struct item* n, int key, int data)
{
    n->key = key;
    n->data = data;
    n->next = h;
    return n;
}

并像这样使用它:

int main()
{
    struct item* head = NULL;
    struct item a, b, c;
    head = add_to_front(head, &c, 1, 2);
    head = add_to_front(head, &b, 3, 4);
    head = add_to_front(head, &a, 5, 6);
    printall(head);
    return(0);
}

【讨论】:

  • 非常感谢您的更新。我在 python 中完全理解了链表,但很难将它翻译成 C。我相信多亏了你的回答,我现在有了更好的理解。
猜你喜欢
  • 2014-08-24
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多