私はc(およびこのサイト)にかなり慣れていないため、セグメンテーション違反で多くの問題を抱えています。数値のリンク リストを作成し、値を昇順で挿入するプログラムを作成しています。
void insert(struct element **head, struct element *new){
if((*head)->next == NULL && (*new).i > (*(*head)->next).i){
(*head)->next = new;
return;
}
if((*head)->next == NULL && (*new).i < (*(*head)->next).i){
new->next = (*head)->next;
*head = new;
return;
}
struct element *prev = *head;
struct element *current = (*head)->next;
while(current->next != NULL){
if((*new).i < (*current).i){
prev = current;
current = current->next;
} else if((*new).i > (*current).i){
new->next = current;
prev->next = new;
}
}
}
int main (void){
struct element **head;
int value;
printf("%s", "TEST" );
printf("%s" , "Please type in an integer value. ");
scanf("%d" , &value);
printf("%s", "TEST" );
do{
printf("%s", "TEST" );
struct element *new;
if((new = malloc(sizeof(struct element))) == NULL){
return(NULL);
}
printf("%s", "TEST" );
(*new).i = value;
printf("%s", "TEST" );
if(head == NULL){
*head = new;
printList(*head);
} else if(value <= 0){
printListBackwards(*head);
}
else {
insert(head, new);
printList(*head);
}
} while(value > 0);
挿入などでロジックが正しいかどうかについての助けは必要ありません。プロンプトの後に整数を入力するとすぐにセグメンテーション違反が発生するため、実際にテストする機会さえありませんでした。ファンキーに見えることはわかっていますが、仕様では、構造体 (リンクされたリストの先頭) へのポインターへのポインターを使用する必要があります。