如何在C中打印链接列表?

时间:2017-10-10 08:08:48

标签: c linked-list

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

typedef struct Node {
    int data;
    struct Node* next;
} Node, *LinkedList;

void CreateList(LinkedList N, int n)
{
    N = (LinkedList)malloc(sizeof(Node));
    N->next = NULL;
    LinkedList new = N;
    Node *p;
    for (int i = 0; i < n; ++i) {
        p = (Node *)malloc(sizeof(Node));
        scanf("%d", &(p->data));
        new->next = p;
        new = p;
    }
    new->next = NULL;
}

int main()
{
    LinkedList list;
    CreateList(list, 20);
    printf("%d", list->data);
    return 0;
}

如您所见,我想创建一个链表并使其成为一个功能。

但是当我&#34; printf&#34;链表的数据,它无法显示我想要的内容。

你能帮助我吗?

2 个答案:

答案 0 :(得分:2)

M. Oehm指出,直接问题是你将列表对象传递给create函数。 create函数创建列表,但由于list对象未返回main,main无法查看列表。要实现您的目标,请执行以下操作:

在main中,将列表声明为:

LinkedList *N;    // a pointer

将create as声明为:

void CreateList(LinkedList **N, int n)    // address of a pointer that receives the value

并在创建中取消引用它:

    *N = malloc(sizeof(Node));    // assign the value to the pointer in main

现在从main调用它:

    CreateList(&N, 20);    // pass the address of the pointer

我进一步注意到你传递了一个int,即列表中元素的数量,但是列表通常是针对未知数量的元素。所以你应该阅读直到文件结束。

(创建中的所有其他必要修改我留给您。)

答案 1 :(得分:0)

谢谢大家!!我解决了这个问题,这是我的代码。

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

typedef struct Node {
    int data;
    struct Node* next;
} Node;

void create(Node* *head, int n)
{
    *head = malloc(sizeof(Node));
    (*head)->next = NULL;
    Node* new = *head;
    Node* p;
    for (int i = 0; i < n; ++i) {
        p = malloc(sizeof(Node));
        scanf("%d", &(p->data));
        new->next = p;
        new = p;
    }
}

int main()
{
    Node* list;
    create(&list,20);
    printf("%d", ((list->next)->next)->data);   //for test
    return 0;
}