关于C列表的练习
我需要有关链接列表的以下代码的帮助:关于C列表的练习,c,list,linked-list,C,List,Linked List,我需要有关链接列表的以下代码的帮助: #include <stdlib.h> #include <stdio.h> struct nodo { int d; struct nodo *next; }; struct nodo *full(); int main() { struct nodo *l; /* l=(struct nodo *)malloc(sizeof(struct nodo)); */ l = full();
#include <stdlib.h>
#include <stdio.h>
struct nodo {
int d;
struct nodo *next;
};
struct nodo *full();
int main()
{
struct nodo *l;
/* l=(struct nodo *)malloc(sizeof(struct nodo)); */
l = full();
while(l!=NULL) {
printf("-->%d\n", l->d);
l =l->next;
}
system("PAUSE");
}
struct nodo *full()
{
int i;
struct nodo *head, *nes;
head = (struct nodo *)malloc(sizeof(struct nodo));
head->next = NULL;
for(i = 1; i < 5; i++) {
nes = (struct nodo *)malloc(sizeof(struct nodo));
printf("Insert the %d element:\n", i);
scanf("%d", &nes->d);
nes->next = head;
head = nes;
}
return head;
}
为什么我会得到最后一个号码?我的代码怎么了?正如@Vinska在评论中指出的那样,
full()
的第3行是不必要的;它正在创建一个额外的节点
有问题的路线是
head=(struct nodo*)malloc(sizeof(struct nodo))代码>
相反,说
head=NULL
使用现有代码,链接列表有5个元素。第一个是在前面提到的行上创建的。如预期的那样,其余四项在循环中创建,总共有5个元素
9708864
号是一个垃圾值。它是调用malloc()
时内存中发生的任何事情。这就是为什么您必须初始化所有变量!或者,在这种情况下,使用memset()
或calloc()
将这些块设置为某个正常值。(但无论如何,这一行在这里是完全多余的。)
祝你好运 在您的代码中,我看不到您正在保留链表的开头。我会这样做:
struct nodo *full()
{
int i;
struct nodo *head, *nes;
head = (struct nodo *)malloc(sizeof(struct nodo));
nes = head;
for(i = 1; i < 5; i++) {
nes->next = (struct nodo *)malloc(sizeof(struct nodo));
printf("Insert the %d element:", i);
scanf("%d", &nes->d);
printf("%s","\n");
nes = nes->next;
}
return head;
}
struct nodo*full()
{
int i;
结构节点*head,*nes;
head=(结构节点*)malloc(sizeof(结构节点));
nes=头部;
对于(i=1;i<5;i++){
nes->next=(结构节点*)malloc(sizeof(结构节点));
printf(“插入%d元素:”,i);
scanf(“%d”和&nes->d);
printf(“%s”,“\n”);
nes=nes->next;
}
回流头;
}
这将创建列表的标题,但随后使用“正在运行”或“当前”列表指针(nes)作为列表创建者
创建列表时,head仍然指向列表的头部
我做了另一个修改,以便在您输入数字后发生行终止符。这是家庭作业吗?另外:1。无需强制转换malloc的结果,2。在调用full()
之前,无需malloc
,3。您没有调用free()
…@EitanT当然是;如果不是,OP就不敢强制转换malloc()的返回值。@EitanT我总是强制转换malloc的结果,因为是的,这是一个家庭作业,而且如果我不强制转换,我的编译器会返回以下错误:从void*'到nodo*'的无效转换我应该在哪里调用free?@wild91你的是哪种蹩脚的C编译器?Vult*必须隐式兼容任何指针类型。@ WELID91可能是用C++编译器编译的吗?代码>无效*
不需要强制转换到另一个指针。此外,我还冒昧地格式化了您的代码。下次标记为[标记:家庭作业]。
struct nodo *full()
{
int i;
struct nodo *head, *nes;
head = (struct nodo *)malloc(sizeof(struct nodo));
nes = head;
for(i = 1; i < 5; i++) {
nes->next = (struct nodo *)malloc(sizeof(struct nodo));
printf("Insert the %d element:", i);
scanf("%d", &nes->d);
printf("%s","\n");
nes = nes->next;
}
return head;
}