Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Inserting into linked list in ascending order

Tags:

c

linked-list

I am trying to create a program that inserts numbers into a linked list in ascending order. This is my insert function. It works for inserting some numbers but not others. I think it has something to do with the last part, but i cant figure it out.

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;

}
like image 525
StackOverflower Avatar asked Nov 30 '25 20:11

StackOverflower


1 Answers

Part of the following bad

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

e.g. to fix like this:

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

or

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;
like image 118
BLUEPIXY Avatar answered Dec 02 '25 12:12

BLUEPIXY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!