How to Insert a node into alternating linked list after the current node?
How to Insert a node into alternating linked list after the current node?
I am writing a linked list function that alternates the nodes odd/even.For example if the input was 6->7->5->3->6->2->9->1
it would output 6->7->6->5->2->3->5->9->1
. The issue I am having is when I run my code I get 6->6->7->2->5->3->5->9->1
.I know the issue stems from the node being inserted before the 7. When it should be inserted after the 7. However, I can't seem to figure out how this is done. How would I go about inserting it after the 7?
6->7->5->3->6->2->9->1
6->7->6->5->2->3->5->9->1
6->6->7->2->5->3->5->9->1
Here is a copy of my function. I am pretty for sure the issue is in the final if loop.
void InterleaveOddsAndEvensInOrigOrder(Node*& headPtr)
{
if(headPtr ==0 || headPtr->link == 0)
{
cout << "list is empty" << endl;
return;
}
Node* cur = headPtr;
Node* post = 0;
Node* postPred = 0;
Node* pred = 0;
while(cur != 0 && cur->link !=0)
{
if(cur->data % 2 == 0)
{
if(cur->link->data % 2 ==0)
{
post = cur;
postPred =0;
while(post !=0 && post->data % 2 == 0)
{
postPred = post;
post = post->link;
}
}
}
else
{
if(cur->link->data % 2 !=0)
{
post = cur;
postPred =0;
while(post !=0 && post->data % 2 !=0)
{
postPred= post;
post = post->link;
}
}
}
if(post !=0)
{
if(pred== 0)
{
postPred->link =post->link;
post->link = cur;
}
else
{
postPred->link =post->link; // The issue is somewhere in here
pred->link =post; //
post->link =cur; //
}
}
pred = cur;
cur = cur->link;
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.