简体   繁体   中英

Sorted Linked List position

I started learning about linked lists and I am having a problem with insertion at the right position in ascending or descending order. Maybe I haven't understood it right. Could you please help me understand the procedure here.

void insert(int x) {
Node* temp = (Node*) malloc(sizeof(Node));
Node* prev = NULL;
Node* curr = head;

if(head!= NULL){
    prev = curr;
    while(prev != NULL){
        prev = prev->next;
    }

    if(prev->data > x){
        temp->data = x;
        temp->next=head;
        head=temp;
    }else{
        temp->data = x;
        temp->next = NULL;
        prev->next = temp;
    }

}else{
    head = temp;
}
}

Your code has a lot of bugs. I think its better to add my version of code rather than pointing out bugs in your code. Here is my code.

void insert(int x)
{
    Node* temp = (Node*) malloc(sizeof(Node));
    temp->data = x;
    temp->next = NULL;
    Node* curr=head;
    if(curr==NULL)//if this were the first element...
    {
        head = temp;
        return;
    }
    if(curr->data > x)
    //special case:
    //adding element at the head itself.
    //you need to change the head pointer then.
    {
        temp->next = curr;
        head = temp;
        return;
    }
    while(curr->next!=NULL)
    {
        if(curr->next->data > x)
        {
            temp->next = curr->next;
            curr->next  =temp;
            return;
        }
        curr = curr->next;
    }
    if(curr->next==NULL)
    //adding the element at the end...
    {
        curr->next = temp;
        return;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM