【发布时间】:2020-06-17 09:02:34
【问题描述】:
我尝试对上述问题进行编码,但出现分段错误。以下是我编写的代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct oddeven
{
int data;
struct oddeven *link;
};
typedef struct oddeven m;
int main()
{
int z;
m *head=NULL,*ptr,*current;
m *x,*y,*q,*head1=NULL,*current1,*head2=NULL,*current2;
while(1)
{
int ch;
ptr=(m*)malloc(sizeof(m));
printf("Enter the data: ");
scanf("%d",&ptr->data);
ptr->link=NULL;
if(head==NULL)
{
head=ptr;
current=ptr;
}
else
{
current->link=ptr;
current=ptr;
}
printf("Do you want to continue?Y=1/N=0");
scanf("%d",&ch);
if(ch!=1)
break;
}
x=head;
while(x!=NULL)
{
z=x->data;
if(z%2==0)
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head1==NULL)
{
head1=ptr;
current1=ptr;
}
else
{
current1->link=ptr;
current1=ptr;
}
}
else
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head2=NULL)
{
head2=ptr;
current2=ptr;
}
else
{
current2->link=ptr;
current2=ptr;
}
}
x=x->link;
}
y=head1;
q=head2;
while (y!=NULL)
{
printf("%d\t",y->data);
y=y->link;
}
printf("\n");
while (q!=NULL)
{
printf("%d\t",q->data);
q=q->link;
}
}
我不知道我哪里出错了。任何帮助将非常感激。 它接受输入,但之后它说分段错误。将给定的单链表拆分为两个,我可以分别存储奇数和偶数。我尝试了不同的方法,但无法让它工作。
【问题讨论】:
-
为什么拆分列表时需要分配更多的节点内存?您可以简单地将每个节点重新链接到“偶数”列表或“奇数”列表。
-
@Gaming DEITY if 语句中有错字。 if(head2=NULL) 必须是 if(head2==NULL)
-
@Gaming DEITY 请注意,您的方法不会执行原始列表的拆分。
-
这能回答你的问题吗? Uninitialized local variable error
标签: c data-structures singly-linked-list