Inserting into a Linked List while Maintaining Ascending Order

  1. The last assignment in this course will help you understand insertion in linked list by inserting in an ordered list.

    These notes show you have you what you must do, You have to figure out the details using what you have learned.

  2. What do you want to achieve when you insert a new element in an ordered linked list:



  3. What do you need to do to insert in an ordered list:

    1. Find the element p2 in the list where:
      • that has a value greater than or equal to the new element
      • Its preceeding element p1 has a value smaller than or equal to the new element

    2. Make the precceding element p1 point to the new element (the new element will thus "follow" this element)

    3. Set the "next" linkage variable in the new element to p2 to indicate that p2 follows the new element

  4. These 2 cases must be handled differently when inserting in an ordered list:

    In all other cases, the variable head does not change in value and can be handle by the insertion technique above.

  5. SPECIAL CASE 1: inserting in an EMPTY list:

  6. SPECIAL CASE 2: inserting at start in an non-empty list:

  7. NOTE: you handle special cases using an if-statement:

          if ( .... special case 1 detected ... )
    	 code to handle insert for special case 1
          else if ( .... special case 2 detected ... )     
    	 code to handle insert for special case 2
    	 code to handle insert for all other cases