insertFront func

closed account (GvCfSL3A)
I'm trying to create a doubly linked list. the issue im having is with the insertFront function which takes a listref and an int data (the value you want to add) as parameters. The idea is to insert it at the front of the list and the problem is it's inserting it successfully but not linking to the nodes behind it.
here's the source:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void insertFront(ListRef L, int data){
   NodeRef N = newNode(data);
   if( L==NULL ){
      printf("List Error: calling insertFront() on NULL ListRef\n");
      exit(1);
   }
   else if( isEmpty(L) ) { 
	   L->front = L->back = N; 
	   L->length++;
   }
   else {
	   N->next = L->front->prev;
	   L->front->prev = N->next;
	   L->front = N;
   }
   
}


where front is the first node and next and prev are parts of the node that reference next and previous (next being rightward direction obviously).
You should really walk through the logic of that second else clause again.

What does : A = B; B = A; accomplish?
Last edited on
closed account (GvCfSL3A)
what do you mean?
all I'm doing is pointing N to be in front of front and then front's prev to N's next and then setting first node to N?
No, you're not.

Assuming that newNode assigns
1
2
N->next=NULL;
N->prev=NULL; 
(it should)

Line 12 assigns N->next = front->prev (which should be NULL).
Line 13 assigns front->prev = N->next (which should still be NULL).

What you are trying to to is point front->prev to the new node and point N->next to the old front value.

You also forgot to increment the count.
Last edited on
Topic archived. No new replies allowed.