不明点
c言語でリスト構造を用いた挿入ソートを作っています。
sort関数内に誤りがあり、segmentation faultを返してしまいます。
誤りを指摘していただければと思います。
よろしくお願い致します。
c
1#include <stdio.h> 2#include <stdlib.h> 3 4typedef struct _cell { 5 int element; 6 struct _cell *next; 7}cell; 8 9typedef struct _list{ 10 cell *head; 11}list; 12 13list* create() { 14 list *L = (list *)malloc(sizeof(list)); 15 L->head = (cell *)malloc(sizeof(cell)); 16 L->head->next = NULL; 17 L->head->element = -1; 18 return L; 19} 20 21void addFirst(list *L, int element) { 22 cell *add = (cell *)malloc(sizeof(cell)); 23 add->element = element; 24 add->next = L->head->next; 25 L->head->next = add; 26} 27 28 29 30void print(list *L) { 31 cell *ptr = L->head->next; 32 while(ptr != NULL) { 33 printf("%d ", ptr->element); 34 ptr = ptr->next; 35 } 36 printf("\n"); 37} 38 39void sort(list *L) { 40 cell *ptr = L->head->next->next; 41 cell *prev = L->head->next; 42 while(ptr != NULL){ 43 while(prev->element > ptr->element) { 44 prev->next = prev; 45 prev = ptr; 46 } 47 ptr = ptr->next; 48 } 49 printf("%d ", ptr->element); 50} 51 52int main() { 53 list *L = create(); 54 55 addFirst(L, 5); 56 addFirst(L, 3); 57 addFirst(L, 5); 58 addFirst(L, 6); 59 print(L); 60 sort(L); 61 62 return 0; 63}

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/26 05:06 編集
2019/04/26 07:24
2019/04/28 10:59