作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#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;
}
如您所见,我想创建一个链表并将其设为一个函数。
但是当我“printf”链接列表的数据时,它无法显示我想要的内容。
你能帮我吗?
最佳答案
正如 M. Oehm 指出的那样,直接问题是您将列表对象传递给 create 函数。 create函数创建列表,但是由于列表对象没有返回给main,所以main看不到列表。要实现您想要的目标,请执行以下操作:
在 main 中,将列表声明为:
LinkedList *N; // a pointer
声明创建为:
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,即列表中的元素数量,但列表通常是为未知数量的元素创建的。所以你应该读到文件末尾。
(创建中所有其他所需的修改我留给您。)
关于c - 如何用C语言打印链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46661629/
我是一名优秀的程序员,十分优秀!