#include <stdio.h>
#include <stdlib.h>
struct linked {
int data;
struct linked *next;
}
*head,*ptr,*tmp;
void display(struct linked *head)
{
tmp=malloc(sizeof(struct linked));
tmp=head;
do
{
printf("%d ",tmp->data);
tmp=tmp->next;
} while(tmp->next!=NULL);
}
struct linked *createlist(struct linked *head)
{
int i,ch;
ptr=malloc(sizeof(struct linked));
//head=(struct linked *)malloc(sizeof(struct linked));
head=ptr=tmp=NULL;
printf("Enter number of elements you want in the list!");
scanf("%d",&ch);
printf("Enter the elements!n");
for(i=0;i<ch;i++)
{
int ele;
tmp=malloc(sizeof(struct linked));
printf("Enter the element %d= ",i+1);
scanf("%d",&ele);
tmp->data=ele;
ptr->next=tmp;
ptr=tmp;
ptr->next=NULL;
if(head==NULL)
head=ptr;
}
return head;
}
int main(void)
{
// your code goes here
head=malloc(sizeof(struct linked));
head=createlist(head);
display(head);
return 0;
}
这里的问题是我不知道我是否正确分配了内存,或者插入节点是否有任何问题。请帮助我是新手。请就如何在代码中调试运行时错误以及如何在实际位置找到它们提出建议。谢谢。
编辑:我收到错误。首先,我不必要地分配内存。到头和PTR。同样在创建列表() 中,我正在使用
createlist(struct linked *head)
调用为创建列表(头)从主()。这实际上导致了价值的调用。这就是为什么即使在创建列表之后,也没有调用 display(),因为 createlist() 中的 head 是函数的本地部分,因此全局 head 没有占据列表的前面。因此,无法遍历,这会产生错误。谢谢大家的帮助。
试试这段代码而不是你的代码...
#include <stdio.h>
#include <stdlib.h>
typedef struct linked {
int data;
struct linked *next;
};
struct linked *head,*ptr,*tmp;
void display()
{
tmp=head;
do
{
printf("%d ",tmp->data);
tmp=tmp->next;
} while(tmp!=NULL);
}
void createlist()
{
int i,ch;
printf("Enter number of elements you want in the list!");
scanf("%d",&ch);
printf("Enter the elements!n");
for(i=0;i<ch;i++)
{
int ele;
tmp=(struct linked*)malloc(sizeof(struct linked));
printf("Enter the element %d= ",i+1);
scanf("%d",&ele);
tmp->data=ele;
tmp->next=NULL;
if(head==NULL){
head=tmp;
ptr=head;
}
else{
ptr->next=tmp;
ptr=ptr->next;
}
}
//return head;
}
int main(void)
{
// head=malloc(sizeof(struct linked));
createlist();
display();
return 0;
}
在创建链表时,您必须记住一些情况。
1 - 第一次当链表创建 head 时为 NULL,并据此采取行动 即在for loop
if
条件下给出的代码
2 - 创建头节点后,您必须将所有剩余节点附加到上次创建的链接列表的末尾 即在条件in for loop
else
给出的代码
如果你创建一个全局变量,那么就不需要将这些变量作为参数传递给函数
全局变量对每个函数都是可见的。