Thread: inserting in order a linked list

  1. #1
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007
    Posts
    85

    inserting in order a linked list

    I have written a funciton : insert_in_order(*list_t, int) that takes a value and inserts it in order into a linked list, although becuse i am new to them, I'm not aure about the validity of this statement:
    if (ptr->data<value && ptr->next->data>value) which i used to find the correct position to insert the data. Is it valid?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well you'll need to check for duplicates, meaning one of those tests won't work:

    1 -> 3

    Trying to insert 3 here will fail your test.

    You also have to consider that ptr->next might be NULL, so you can't just automatically jump to ptr->next->data without checking that first.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007
    Posts
    85
    i ammended the code and have thusfar untested :
    Code:
    list_t
    *insert_in_order (list_t *list, int value) {
    	node_t *new, *ptr;
    	new = malloc(sizeof(*new));
    	assert(list!=NULL);
    	new->data=value;
    	ptr=list->head;
    	if (ptr->data<value)
    /*must be smaller than the head, insert it at the head and stop*/
    	{
    		list = insert_at_head(list, value);
    	}
    	while (ptr!=NULL)
    	{
    		if (ptr->data==value)
    /*equal values, so it doesn't matter if it is put in before or after, we'll do it before*/
    		{
    			new->next=ptr->next;
    			ptr->next=new;
    			break;
    		}
    		
    		if (ptr->data<value && ptr->next->data>value)
    /*must be the right place to insert*/
    		{
    			new->next=ptr->next;
    			ptr->next=new;
    			break;
    		}
    		else 
    		{
    			ptr = ptr->next;
    		}
    	}
    /*Reached end of the line wihtout a larger value ahead, insert at foot*/
    	list = insert_at_foot(list, value);
    	return list;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 01:21 PM
  2. deleting a node in linked list
    By BoneXXX in forum C Programming
    Replies: 18
    Last Post: 12-17-2007, 12:30 PM
  3. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  4. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM
  5. 1st Class LIST ADT
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2001, 07:29 PM