#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 工作吗?谢谢
最佳答案
您在这里分配一个指向结构的指针:
h = h.next;
h
类型是 struct 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);
}
关于c - 结构单向链表。为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462254/