C – 按升序插入链表

我正在尝试创建一个程序,按升序将数字插入链表。 这是我的插入function。 它适用于插入一些数字但不能插入其他数字。 我认为它与最后一部分有关,但我无法弄明白。

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 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 next; } newNode->next = temp->next; temp->next = newNode; return head; } 

部分以下不好

 //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; 

例如,像这样修复:

 node *temp ,*prev; temp = head; while(temp != NULL && temp->value <= value) { prev = temp; temp = temp->next; } newNode->next = temp; prev->next = newNode; 

要么

 node *temp ,*prev; temp = head->next; prev = head; while(temp != NULL && temp->value < value) { prev = temp; temp = temp->next; } newNode->next = temp; prev->next = newNode; 

您需要在最后一个while循环中检查temp->next->value

 //This code of mine works perfectly. void insertInAscOrder(int val) { node *new1; node *temp; node *previous; //create new node new1 = (node *)malloc(sizeof(node)); //check whether node is created or not if(new1 == NULL) { printf("Insufficient memory."); return; } //Updating different parts of the node new1 -> info = val; new1 -> next = NULL; //checking whether the node created is only node or not if (start == NULL) { start = new1; } //If value is less than the value of first node else if(val < start -> info) { new1 -> next = start; start = new1; } else { previous = start; temp = start -> next; //Go to the position where node is to be inserted while(temp != NULL && val > temp -> info) { previous = temp; temp = temp -> next; } //Insert the node at particular position if(temp == NULL) { previous -> next = new1; } else { new1 -> next = temp; previous -> next = new1; } } } 

如果你首先实现(和测试)函数会更好,例如: push_front()insert() (insert before)和push_back() ,(可能是advance (Node* curr, int steps); )然后简单地考虑插入的所有可能性,即:

  • 空列表(当前节点是第一个,所以只是push_front / back()
  • 迭代( advance() )从头到尾的所有元素,直到:
    • 找到值大于new的元素,在它之前insert()
    • 到达最后一个元素, push_back()

在你的新函数insert_ordered()