Insert into a certain position in a double linked list!

Hey I'm having trouble inserting a node in a nth position into a double linked list. My for loop is
giving me an exception handler error and I can't link the node after the new node is inserted back to the new node.
Here is my code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void mylist::insertpos(const int &pos, const string &s, const int & c)
{
  listnode* temp1 = new listnode(s,c);
  temp1->s =s;
  temp1->next = NULL;

   //If trying to insert at the first position 
  if(c ==0) {
	  temp1 ->next = head;
	  head = temp1;
	  return;
  }
  
  listnode* temp2 = head;
  listnode* temp3;
  
  for(int i = 0; i < c-2; i++)
  {	
	  temp2 = temp2-> next;
  }

  temp1->next = temp2 ->next;
  temp2->next = temp1;
  temp3 = temp1->next;
  temp1 ->prev = temp2;
  temp3 ->prev = temp1;
  
  
  cout << "insertpos is not supported.\n";
}


Do anyone have any suggestions?
I attached my header file incase you need to see the definitions for my objects.
Last edited on
This might help http://www.cplusplus.com/forum/general/28912/. Its honestly hard to recall what temp1, 2, and 3 mean looking at lines 22-26.

or this http://stackoverflow.com/questions/5404491/inserting-node-into-doubly-linked-list
Last edited on
why are you checking for c

//If trying to insert at the first position
if(c ==0) {
yeah that's really suppose to be pos, I forgot to change it before I made the post.
First of all, post corrected code (with pos used where it's required) and better variable names.

But while I'm here:
- There's no point passing an int by const reference. That should only be done for class types, not built-in types like int, double, etc.
- line 4 and 5 shouldn't be needed if you have a constructor (which appears to be the case from line 3)
- temp3 is v prob unnecessary
- when you add a new node at the head, you're not setting up prev
- what happens when you try to insert after a node which is at an index past the end of the list?

Andy
Topic archived. No new replies allowed.