* 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;



while (newnode -> val < current -> next -> val )
current = current -> next;

newnode -> next = current -> next;
current-> next= newnode;
list= current;

return list;


Edited by __avd: Added [code] tags.

6 Years
Discussion Span
Last Post by abhimanipal

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:




So you cover adding to the list before the current first node, adding to the middle, and adding to the very end of the list.

Work through adding 0 to the list, noting the ADDRESSES of the nodes, and what your program is doing with them, as you step through your program.

When that's working, repeat with 25 and 55.

Trouble shooting is a very important skill for programming, and it takes practice. A simple problem like this is the PERFECT time to help develop that skill, and you will learn to be a better programmer, as well.

Edited by Adak: n/a


Thanks Adak, but I already did tried trouble shooting it, this is the time when I get the core dumped error. this is my main.

        struct node * myList = NULL;

        myList = insert (7,myList);

        myList = insert (1,myList);

        myList = insert (4,myList);

    myList = insert (2,myList);

        myList = insert (5,myList);

Edited by mike_2000_17: Fixed formatting


In your while loop (lines 36 - 39) you are not checking to see if you hit NULL or not

WHen you do current = current->next check to see current->next is not equal to NULL

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.