如果我将反向函数发送到列表中,我会得到预期的输出。但是如果我使用我的 reverseNth 函数,我只会得到列表中的第一件事。ReverseNth 按部分反转列表。例如,如果我有一个列表 = <1 2 3 4 5>。调用 reverse() 将输出 <5 4 3 2 1>。在列表中调用 reverseNth(2) 应该给出 <2 1 4 3 5>。
相关代码:
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;
}
}
反向代码:
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;
}