Connecting Tech Pros Worldwide Help | Site Map

inserting an item after a specific position in linked List

Member
 
Join Date: Mar 2007
Posts: 43
#1: Oct 31 '07
hi ,
i wanna ask about how to insert an item in a linked list..
this item should be inserted after a specific position..

any ideas??
Familiar Sight
 
Join Date: Apr 2007
Posts: 188
#2: Oct 31 '07

re: inserting an item after a specific position in linked List


Quote:

Originally Posted by maloov

hi ,
i wanna ask about how to insert an item in a linked list..
this item should be inserted after a specific position..

any ideas??

In general you break the link at the place where you want to insert your new node and form new links from your new node to the places where you broke the link.

so if you have A -> B -> C -> E and you want to insert D you break the link from C-> E and make C -> D -> E

The details of how it's actually accomplished will vary depending upon the implementation of the list.
Member
 
Join Date: Mar 2007
Posts: 43
#3: Oct 31 '07

re: inserting an item after a specific position in linked List


thanx mac..

but ma problem actually in breaking the link..
how to break it..
we should assign something to another..
here where i'm kinda lost..
Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#4: Oct 31 '07

re: inserting an item after a specific position in linked List


Let's take the above example of the following list:

A->B->C->E->(rest of the list)

You want to insert D.

First you have to get a node* to point to C by going first to A, then following the node* next pointers until you get to C. So let's look at the situation:

Before the insert:

Expand|Select|Wrap|Line Numbers
  1. C:
  2. Has some data (C)
  3. next points to E
  4.  
  5. E:
  6. Has some data (E)
  7. next points somewhere (it doesn't matter where)
  8.  
  9. D (node to be inserted):
  10. Has some data (D)
  11. next points nowhere (null)
And after the insert:


Expand|Select|Wrap|Line Numbers
  1. C:
  2. Has some data (C)
  3. next points to D
  4.  
  5. E:
  6. Has some data (E)
  7. next points somewhere (it doesn't matter where)
  8.  
  9. D (node to be inserted):
  10. Has some data (D)
  11. next points to E
Hmm...only two things changed: C's next pointer, and D's next pointer. The data didn't change anywhere, and E wasn't changed.

Can you figure it out from here? It's just a few simple assignment statements.
Member
 
Join Date: Mar 2007
Posts: 43
#5: Oct 31 '07

re: inserting an item after a specific position in linked List


aha ..

ok i've got it now..
thanx buddy..
Reply