insertAt front in a duobly linked list

Hi Everyone,
I tried to insert a node at front in doubly linked list and I think I did the first part when the list isEmpty(). But the second part I was trying from yesterday but I did not get it.



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
31
32
33
  void List< NODETYPE >::insertAtFront( const NODETYPE &value )
{
   ListNode< NODETYPE > *newPtr = getNewNode( value ); // new node
  // ListNode< NODETYPE > *current 

   if ( isEmpty() ) // List is empty
	   {
		  
		  firstPtr = newPtr;
		  lastPtr = newPtr;
		  newPtr ->nextPtr = NULL;
		  newPtr ->prevPtr = NULL;
		  newPtr ->data = value;
	   }
	   // new list has only one node
   else // List is not empty
     {
	 ListNode< NODETYPE > *newNode = firstPtr;
		  
	     while ( newNode ->nextPtr != lastPtr->nextPtr)
		  newNode = newNode ->nextPtr;

		 if(newNode == firstPtr)
			{
					
				newNode ->nextPtr = firstPtr->nextPtr;
				newNode ->prevPtr = NULL;
				firstPtr = newNode;
				newNode ->data = value;
			}

      } // end else
} // end function insertAtFront 


Your help is highly appreciated.
Why do you have to go till end for adding in front of the linked list.

will something like this not work ?

1
2
3
4
newPtr->next = firstptr;
newPtr->prev = null;
firstptr->prev = newPtr;
firstptr = newPtr;


Topic archived. No new replies allowed.