If I send my reverse function on a list I get the expected output. But if I use my reverseNth function I only get the first thing in my list. ReverseNth reverses the list in sections.
For example if I have a list = <1 2 3 4 5>. Calling reverse() will output <5 4 3 2 1>. Calling reverseNth(2) on the list should give <2 1 4 3 5>.
Relevant Code:
void List<T>::reverse( ListNode * & startPoint, ListNode * & endPoint )
{
if(startPoint == NULL || startPoint == endPoint)
return;
ListNode* stop = endPoint;
ListNode* temp = startPoint;
startPoint = endPoint;
endPoint = temp;
ListNode* p = startPoint; //create a node and point to head
while(p != stop)
{
temp = p->next;
p->next = p->prev;
p->prev = temp;
p = p->next;
}
}
ReverseNth code:
void List<T>::reverseNth( int n )
{
if(head == NULL || head == tail || n == 1 || n == 0)
return;
if(n >= length)
{
reverse(head,tail);
return;
}
ListNode* tempStart = head;
ListNode* tempEnd;
for(int j = 0; j < length; j += n)
{
// make the end of the section the beginning of the next
tempEnd = tempStart;
// set the end of the section to reverse
for(int i = 0; i < n-1; i ++)
{
// check to make sure that the section doesn't go past the length
if(j+i == length)
i = n;
else
tempEnd = tempEnd-> next;
}
reverse(tempStart, tempEnd);
if( j == 0)
head = tempStart;
if(tempStart == tail)
{
tail = tempEnd;
return;
}
else
tempStart = tempEnd-> next;
}
tail = tempEnd;
}
You’re not using
startPointandendPointin your reverse function. At present, your reverse function reverses the entire list, leaving the oldhead->nextto point to null (since it’s now the end).I’m guessing the reverse function used to reverse the whole list, but was then extended to take an arbitrary start/end point (possibly an overload?).