c - 链表初学者

标签 c list

我刚刚开始学习链表,在创建一个读取链表的函数时遇到问题。当我从开关中选择读取功能时,它会变成空白,什么也不会发生(如果我将代码放在 main () 中,它将起作用)。我做错了什么?

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

struct nod
{
    int nr;
    struct nod *next;
} nod;

int read(struct nod *p)
{
    while(p->next != NULL )
    {
        printf("%d", p->nr);
        p=p->next;
    }

    printf("%d", p->nr);
}

int main()
{
    struct nod* trei = NULL;
    struct nod* unu = NULL;
    struct nod* doi = NULL;
    struct nod* p = NULL;
    struct nod* n = NULL;
    unu = (struct nod*)malloc(sizeof(struct nod));
    doi = (struct nod*)malloc(sizeof(struct nod));
    trei = (struct nod*)malloc(sizeof(struct nod));
    p = (struct nod*)malloc(sizeof(struct nod));
    n = (struct nod*)malloc(sizeof(struct nod));
    unu->nr = 1;
    unu->next = doi;
    doi->nr = 2;
    doi->next = trei;
    trei->nr = 3;
    trei->next = NULL;
    p = unu;
    int meniu = 0;
    while(1)
    {
        printf("1. Read list");
        scanf("%d", meniu);
        switch(meniu)
        {
        case(2):
            read(p);
            break;
        }
    }
    printf("%d", p->nr);
}

最佳答案

一些建议,没有完整的修复。

无需将指针初始化为 NULL,只需一步定义和初始化即可。另外,不要从 void* 进行转换,这是 ma​​lloc 返回的内容。 C 允许您隐式地从 void 指针来回转换;每一次转换都是一个犯错的机会。

struct nod* trei = malloc(sizeof(struct nod));
struct nod* unu  = malloc(sizeof(struct nod));
struct nod* doi  = malloc(sizeof(struct nod));

我不清楚 np 是否需要分配。我认为你的意思是它们指向分配的节点。

您可以使用 c99 语法在一条语句中初始化您的结构。我认为这个表格更加清晰。

*unu = (struct nod) { .nr = 1, .next = doi };
*doi = (struct nod) { .nr = 2, .next = trei };
*trei = (struct nod) { .nr = 3, .next = NULL };

帮自己一个忙,不要调用你的函数read,除非你 意味着覆盖标准的read(2)函数。你不 正在阅读,你正在报道。也许称之为“打印”。

循环很尴尬。你想要

while(p != NULL )
{
    printf("%d", p->nr);
    p=p->next;
}

有两个原因:

  1. 防止传递的 p 为 NULL
  2. 打印trei

p指向trei时,p->next为NULL。你不想退出 然后循环;您想要打印 trei,分配 p = p->next,并且 测试p。然后你可以删除后面的printf("%d", p->nr); 循环,正如您必须的那样,因为 p 将为 NULL。 :-)

我没有发现你的“阅读”功能有任何其他问题,没有理由 它不会打印您的数据。我会再撒一些 printf 语句,并每次调用 fflush(3),以确保您看到 他们。我敢打赌你的程序并没有按照你的想法去做。不至于 不过,担心。如果你喜欢编程,你会发现它很漂亮 普通的。

关于c - 链表初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54347945/

相关文章:

c - 获取字符串的第一个字符

python - 索引错误: list index out of range in python for strings

Python - 转置各种长度列表的列表 - 3.3 最简单​​的方法

c - scanf ("%[^\n]") 被跳过

c - 无法在多线程程序中捕获 SIGINT 信号

c - 为什么 2nd scanf 在我的程序中不起作用?

c - 声明 char 数组导致 execv() 不起作用

java - 在java中将列表元素分为不同的组

python - 从 Python 3.x 中的文件名切片部分创建列表列表

python - 将不同列表中的选定项目组合成一个新项目