0
私はCを使用して、SortedInsert()関数を書いて、新しいノードを昇順でソートされたリストに挿入しました。機能SortedInsert()の私のコードは以下の通りである:リンクされたリストSortedInsert()関数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node
{
int data;
struct node *next;
};
void push(struct node** head, int data_new) {
struct node* headNode;
headNode = (node*)malloc(sizeof(struct node));
headNode->data = data_new;
headNode->next = *head;
*head = headNode;
}
struct node* BuildFunny() {
struct node*head = NULL;
push(&head, 2);
push(&head->next, 3);
push(&head->next->next, 8);
push(&head->next->next->next, 10);
push(&head->next->next->next->next, 15);
head->next->next->next->next->next = NULL;
return head;
}
void SortedInsert(struct node** headRef, struct node* newNode){
if (*headRef == NULL || (*headRef)->data >= newNode->data){
newNode->next = *headRef;
*headRef = newNode;
}
else {
struct node* current;
current = *headRef;
while (current->next->data <= newNode->data && current->next != NULL){
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
主な機能は次のとおり
int main()
{
struct node* head;
head = BuildFunny();
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = 1;
newNode->next = NULL;
SortedInsert(&head, newNode);
struct node* newNode1 = (struct node*)malloc(sizeof(struct node));
newNode1->data = 6;
newNode1->next = NULL;
SortedInsert(&head, newNode1);
/*
struct node* newNode2 = (struct node*)malloc(sizeof(struct node));
newNode2->data = 20;
newNode2->next = NULL;
SortedInsert(&head, newNode2);
*/
while(head != NULL){
printf("%d ", head->data);
head = head->next;
}
return 0;
}
問題は、私が正しくしかし、正しい順序付きリストに数20を数1〜6を挿入することができています常にエラーが表示されます(コメントを外すとnewNode2はエラーになります)。なぜ15を超える数字を私のリストに挿入できないのか分かりません。誰かが15歳以上の数字をリストの最後に挿入できるように助けてくれますか?
「エラー」。あなたが実際にエラーが何であるか教えてくれれば助けになります。コンパイルエラーですか?ランタイムエラー?もしあればエラーメッセージは何ですか? – kaylum