Web Toolbar by Wibiya

Pages

Thursday, December 15, 2011

Insert a node in a sorted linked list.

Solution #1: Below is the code to insert a node in a linked list sorted in ascending order. The code assumes that the list is not empty initially.

void insert_sorted(struct node** pHead, int n)
{
    struct node* curr = *pHead;
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = n;

    if(*pHead == NULL)
    {
        temp->next = NULL;
        *pHead = temp;
        return;
    }

    if(curr->data > n)
    {
        temp->next = curr;
        *pHead = temp;
        return;
    }

    while(curr->next != NULL)
    {
        if((curr->data < n) && (curr->next->data > n))
            break;

        curr = curr->next;
    }

    temp->next = curr->next;
    curr->next = temp;
}

No comments: