Thursday, August 19, 2010

Best way to enter a node into the middle of a linked list??

What is the best way to place a new node into a linked list where you dont know what the size of the list is.

Best way to enter a node into the middle of a linked list??
The great thing about linked lists are that you don't need to know the size of the list, or any nodes other than the two you will insert between.





All you have to do is adjust the pointers of the two existing to point to the new.





Imagine a case where there are two existing nodes, first and second.





For example:


struct node {


node *next;


data val;


};





struct node first, second, new;


// assign appropriate values to first, second and new





// before insert,


// first.next points to second.


// i.e. list.head = %26amp;first


// first.next = %26amp;second


// second.next = NULL





// To insert a node between first and second, all we have to


// do is change the next pointers


// insert code:


first.next = %26amp;new;


new.next = %26amp;second;





// Now the chain reads:


// list.head = %26amp;first


// first.next = %26amp;new


// new.next = %26amp;second


// second.next = NULL


No comments:

Post a Comment