整数データを連結リストに法則通り格納することを考えてます。
C言語で奇数のデータ同士は昇順に,偶数のデータ同士は降順に並ぶようにリストに挿入する機能を実装中に以下のエラーメッセージが発生しました。
Segmentation fault
該当のソースコード
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct _cell{
int data;
struct _cell *next;
}CELL;
CELL *head;
void show_list()
{
CELL *p;
for(p=head;p!=NULL;p=p->next)
printf("%d\n",p->data);
}
void insert_cell(CELL *p,int d)
{
CELL new_cell;
new_cell = (CELL)malloc(sizeof(CELL));
new_cell -> data = d;
new_cell -> next = p->next;
p -> next = new_cell;
}
void insert_cell_top(int d)
{
CELL new_cell;
new_cell = (CELL)malloc(sizeof(CELL));
new_cell -> data = d;
new_cell -> next = head;
head = new_cell;
}
void insert_data(int d)
{
printf("insert_start\n");
if(head == NULL)
insert_cell_top(d);
else
{
CELL *p = head;
CELL *q = head -> next;
if(d%2==1){
while(q!= NULL&&q->data<d&&q->data%2==1){
p = q;
q = q -> next;
}
}
else{
while(q->data%2==1){
p = q;
q = q -> next;
}
while(q->data>=d&&q!=NULL){
p = q;
q = q -> next;
}
} printf("pointer_set\n"); if(p==head){ if(head->data!=d){ if(head->data%2==0&&d%2==0&&d>head->data)insert_cell_top(d); if(head->data%2==0&&d%2==0&&d<head->data)insert_cell(p,d); if(head->data%2==1&&d%2==1&&d<head->data)insert_cell_top(d); if(head->data%2==1&&d%2==1&&d>head->data)insert_cell(p,d); if(head->data%2==0&&d%2==1)insert_cell_top(d); if(head->data%2==1&&d%2==0)insert_cell(p,d); }else insert_cell(p,d); }else insert_cell(p,d); }
printf("insert_end\n");
}
int main(void)
{
clock_t start,end;
int i;
int x[10];
srand(time(NULL));
for(i=0;i<10;i++){
x[i]=rand()%10;
printf("%d\n",x[i]);
}
start=clock();
for(i=0;i<10;i++){
insert_data(x[i]);
}
end=clock();
printf("%f sec\n",(double)(end-start)/CLOCKS_PER_SEC);
show_list();
return 0;
}
C
試したこと
どこで動作しなくなっているのかみつけたが色々しても治らなかった。
補足情報(FW/ツールのバージョンなど)
while(q->data%2==1){
p = q;
q = q -> next;
}
while(q->data>=d&&q!=NULL){
p = q;
q = q -> next;
}
この部分でSegmentation faultがでていた。
全然わかりません。お力添えいただけますと幸いです、よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー