* 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;
}
hussamat
0
Newbie Poster
Recommended Answers
Jump to PostWelcome 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
Reply to this topic
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.