```
* Asuming the list is sorted in ascending order, inserts n in the list
* at the right position to maintain the ascending and returns the resulted list.
*/
struct node * insert (int n, struct node * list){
struct node * newnode = (struct node *) malloc (sizeof(struct node));
struct node * current = (struct node *) malloc (sizeof(struct node));
current = list;
//int start = current-> val;
newnode -> val = n;
newnode -> next = NULL;
if (newnode-> val < current->val || current == NULL)
{
newnode->next = current;
list = newnode;
}
else if (current -> next == NULL && newnode -> val > current -> val)
{
current ->next = newnode;
newnode -> next = NULL;
}
else
{
while (newnode -> val < current -> next -> val )
{
current = current -> next;
}
newnode -> next = current -> next;
current-> next= newnode;
}
list= current;
return list;
}
```

## Recommended Answers

Jump to Post

Welcome to the forum, Hussamat!;)Now you trouble shoot it:

1) crate a list with 5 nodes and give them 1, 10, 20, 30, 40, values.

2) now try to add three values, working one at a time, until you know it's working correctly:

0:

…

## All 3 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.