我試圖創建一個程序,以升序將數字插入到鏈接列表中。這是我的插入功能。它適用於插入一些數字,但不是其他數字。我認爲這與最後一部分有關,但我無法弄清楚。C - 按升序插入鏈接列表
node* insert(node* head, int value) {
//check if head hasn't been created
if (head == NULL) {
head = malloc(sizeof(node));
if(head == NULL) {
printf("Failed to create head node");
return head;
}
head->value = value;
head->next = NULL;
return head;
}
//create a new node
node *newNode;
newNode = malloc(sizeof(node));
if(newNode == NULL) {
printf("Failed to create node");
return newNode;
}
newNode->value = value;
newNode->next = NULL;
//see if new node should be placed before head
if (value < head->value) {
newNode->next = head;
return newNode;
}
//search through to find correct spot and insert the node
node *temp = NULL;
temp = head;
while(temp->next != NULL && temp->value < value) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
return head;
}
您能否提供一些與預期相同的輸入以及不是哪種輸入的示例? – 2rs2ts