1

如果我将反向函数发送到列表中,我会得到预期的输出。但是如果我使用我的 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;
}
4

1 回答 1

0

您没有在反向功能中使用startPointand endPoint。目前,您的 reverse 函数反转整个列表,使 oldhead->next指向 null (因为它现在是结尾)。

我猜测用于反转整个列表的 reverse 函数,但随后被扩展为采用任意起点/终点(可能是重载?)。

于 2012-09-25T01:27:48.057 回答