0
C는 SortedInsert() 함수를 사용하여 주어진 순서에 따라 정렬 된 새 노드를 삽입합니다. 기능 SortedInsert() 내 코드는 다음입니다 :연결된 목록 SortedInsert() function
#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을 삽입 할 수있다 항상 오류가 발생합니다 (uncomment newNode2 오류가 발생합니다). 왜 15 이상을 내 목록에 삽입 할 수 없는지 모르겠다. 15 살이 넘는 사람들이 목록 끝에 삽입 할 수있게 도와 줄 수 있습니까?
"오류가 발생했습니다." 오류가 무엇인지 실제로 말하면 도움이됩니다. 컴파일 오류입니까? 런타임 오류? 오류 메시지가 있다면 무엇입니까? – kaylum