Saturday, May 26, 2007

Write a C program to insert nodes into a linked list in a sorted fashion

The solution is to iterate down the list looking for the correct place to insert the new node. That could be the end of the list, or a point just before a node which is larger than the new node.

Note that we assume the memory for the new node has already been allocated and a pointer to that memory is being passed to this function.



// Special case code for the head end
void linkedListInsertSorted(struct node** headReference, struct node* newNode)
{
// Special case for the head end
if (*headReference == NULL || (*headReference)->data >= newNode->data)
{
newNode->next = *headReference;
*headReference = newNode;
}
else
{
// Locate the node before which the insertion is to happen!
struct node* current = *headReference;
while (current->next!=NULL && current->next->data < newNode->data)
{
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}

4 comments:

Anonymous said...

just check your code once....

Anonymous said...

just check your code once....

Anonymous said...

Excellent pieces. Keep posting such kind of info on your page.
Im really impressed by your site.
Hi there, You have done an incredible job. I'll definitely digg it and individually recommend to my friends. I am sure they'll be benefited from
this website.

Also visit my site; waist hip ratio calculator

Namita Agrawal said...

All Government jobs Banks , PSU,CPSU,PSC,UPSC,Defence, Exam,Admit cards,India & Others

All Government jobs Banks , PSU,CPSU,PSC,UPSC,Defence & Others or Submit & verify Email for Latest Jobs Alerts

All Examinations Latest updates or Submit & verify Email for Latest Exams Alerts

Examination Planning & strategy or Submit & verify Email for Latest Exam Plan Alerts

Check your Exam results or Submit & verify Email for Latest Exam Results Alerts

Downloads Your Admit card / Hall Ticket or Submit & verify Email for Latest Admit Cards Alerts