【发布时间】:2018-04-02 05:38:30
【问题描述】:
我是数据结构的新手,在实现双链表时遇到了一些麻烦。在获取所有显示分段错误(核心转储)的输入编译器之后。找不到错误。 我搜索了核心转储错误以及分段错误,但没有帮助。 这是我的代码:
struct node
{
int data;
struct node *lptr,*rptr;
};
struct node *head;
void create(struct node *head)
{
struct node *newp,*ptr;
int num,n;
printf("Enter the no. of elements you want to enter :\n");
scanf("%d",&n);
printf("Enter the elements:\n");
while(n)
{
scanf("%d",&num);
n--;
if(head==NULL)
{
newp=(struct node *)malloc(sizeof(struct node));
newp->lptr=NULL;
newp->data=num;
newp->rptr=NULL;
head=newp;
printf("Head created\n");
ptr=head;
}
else
{
while(ptr->rptr)
{
ptr=ptr->rptr;
}
ptr->rptr=(struct node *)malloc(sizeof(struct node));
ptr->rptr->lptr=ptr;
ptr->data=num;
ptr->rptr->rptr=NULL;
ptr=ptr->rptr;
printf("node inserted\n");
}
}
}
void display(struct node *head)
{
struct node *ptr;
ptr=head;
while(ptr->rptr)
{
printf("%d\t",ptr->data );
ptr=ptr->rptr;
}
}
void main()
{
head=NULL;
create(head);
display(head);
}
【问题讨论】:
-
请注意,您有多个名为
head的不同变量。它们没有任何联系。
标签: c data-structures linked-list segmentation-fault