简体   繁体   English

C编程中的简单链接列表结构

[英]Simple link list structure in C programming

This is my first link list program in C, I am trying to initialize the values of the nodes and trying to print it. 这是我在C中的第一个链接列表程序,我试图初始化节点的值并尝试打印它。 however, its not giving me the intended output. 但是,它没有给我预期的输出。 Can anyone let me know where am I going wrong? 谁能让我知道我哪里错了?

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int key;
    struct node *next;
};

typedef struct node NODE;

int main ()
{
    NODE a,b,c;
    NODE *list;
    list=&a;
    list->key = 10;
    list->next = &b;
    list->next->key=20;
    list->next->next=&c;
    list->next->next->key=30;
    list->next->next->next=NULL;
    printf("%d  %d  %d", a,b,c);
   return 0;
}

It prints 10 and 20 with some garbage in between. 它打印10和20之间有一些垃圾。

You really shoulnd't be passing entire structures (the variables a , b and c ) to printf() like that, did that even compile? 你真的不应该将整个结构(变量abc )传递给printf() ,甚至可以编译吗?

You want to pass the integer data: 您想传递整数数据:

printf("%d %d %d\n", a.key, b.key, c.key);

but of course that totally ignores the links between the nodes. 但当然这完全忽略了节点之间的联系。

It would more "interesting", in this context, to have something like: 在这种情况下,它会更像“有趣”,例如:

static void print_list(const NODE *head)
{
  const NODE *prev = NULL;

  for(; head != NULL; prev = head, head = head->next)
    printf("%d ", head->key);
  puts(prev != NULL ? "\n" : "");
}

And then call that from main() after setting list : 然后在设置list后从main()调用它:

print_list(list);  /* or print_list(&a); */

You can also simplify the creation of the linked list: 您还可以简化链接列表的创建:

a.key = 10;
a.next = &b;
b.key = 20;
b.next = &c;
c.key = 30;
c.next = NULL;
list = &a;

This more clearly uses the fact that all nodes are directly available, and drops the hysterical link-following. 这更明显地使用了所有节点都可直接使用的事实,并且放弃了歇斯底里的链接跟踪。

You want to print the values of the 3 structures, that are in the field key of each of them. 您想要打印3个结构的值,这些值位于每个结构的字段键中。 So you need to change the line 所以你需要改变这条线

printf("%d  %d  %d", a,b,c);

with the line 与线

printf("%d  %d  %d", a.key,b.key,c.key);

It is actually strange that you do not get a warning from the compiler, like this one: 实际上很奇怪你没有得到编译器的警告,比如这个:

main.c:20:31: warning: format specifies type 'int' but the argument has type
  'NODE' (aka 'struct node') [-Wformat]

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

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