结构单链表。为什么这不起作用?

问题描述 投票:0回答:1
#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工作吗?谢谢

c struct
1个回答
3
投票

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.