Question

I am having trouble trying to understand how to initialize the prev pointer in a node struct. I see that going forward i set CurrPtr->Next to a new node and that your Current Pointr is set to CurrPtr->Next which is that new node you just made. But How do you go backwards. Is it with this CurrPtr->Prev=CurrPtr?I am just having a hard time visualizing it.

While(cont!=-1)
{
cin>>cont;
CurrPtr->Next=new Node;
CurrPtr=CurrPtr->Next;
}
Was it helpful?

Solution

Making some assumptions here...

Statements like this:

CurrPtr = 

Are saying "I am setting my current position in the list to X".

CurrPtr->Prev = 

or

CurrPtr->Next = 

are building the links from your current node to the previous and next nodes respectively.

Your statement of

CurrPtr->Prev=CurrPtr

Doesn't move you in your list, it just sets the previous node to the current node thereby creating a closed loop where trying to move to Prev will return you to your current node. When you create a new node you also set it's link to the other nodes by linking it to the current node.

While(cont!=-1)
{
cin>>cont;
CurrPtr->Next=new Node;
CurrPtr->Next->Prev=CurrPtr;
}

Once you've made the link you could then move from your current node to the next node and then move back to your starting node since you've set the Prev pointer.

CurrPtr = CurrPtr->Next;
CurrPtr = CurrPtr->Prev;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top