双向链表的反转功能

时间:2012-09-25 01:20:07

标签: c++ linked-list doubly-linked-list

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

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;
}

1 个答案:

答案 0 :(得分:0)

您在反向功能中没有使用startPointendPoint。目前,您的反向函数会反转整个列表,使旧的head->next指向null(因为它现在已经结束)。

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