Link to home
Start Free TrialLog in
Avatar of Gipsy
Gipsy

asked on

Help with pointers

Hi,

If there is a Dummy head in the list. I need to insert a new node pointed by NewPtr at the beginning of the list.

From what I read, I understood that dummy head is used to get exclude the special cases.
So the solution:

NewPtr->next=head;
Head=NewPtr;

is not applicable, coz that is what is being used for the special case.
What would be a similar code segment for the list that uses dummy head.

I have a solution, but i am not sure if it is right:

Head->Next=NewPtr;
NewPtr->Next=Head->Next;


Can you please advise, and if possible explain.
Thanks.

Avatar of tinchos
tinchos

Just a minor change

NewPtr->Next=Head->Next;
Head->Next=NewPtr;

With your code

Head->Next=NewPtr;  // Here you lose the old head->next
NewPtr->Next=Head->Next;  // So you cannot assign it here
ASKER CERTIFIED SOLUTION
Avatar of tinchos
tinchos

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gipsy

ASKER

Thanks, can you briefly explain what your code does, I am new to pointers and trying to understand how it works. Thanks
Well, I believe that this is worth more than 30 points, but that's up to you............ here's my explanation

suppose you have a list with 5 elements

( 1 2 3 4 5 )

and you want to add a new element in the beggining containing 0.

then

before the insertion you have

head->next is pointing to the node containing the 1 (lets call it node1)
node1->next is pointing to the node containing the 2 (lets call it node2)
node2->next is pointing to the node containing the 3 (lets call it node3)

so, in some pseudocode

head->next = node1          // The first element is node1
node1->next = node2
node2->next = node3
and so on

if you want to add a new node containing 0 (lets call it node0 )

then, you want to do

node0->next = node1           // As you want the 0 to be before the 1

and the first element is no longer node1, it is node0, so

head->next=node0

so in the end you have

head->next=node0
node0->next = node1
node1->next = node2
node2->next = node3
and so on

and in this way you represent

( 0 1 2 3 )

I hope its clear enough

any doubts feel free to ask them