【问题标题】:Reverse function for a doubly linked list双向链表的反向函数
【发布时间】:2012-09-25 01:20:07
【问题描述】:

如果我将反向函数发送到列表中,我会得到预期的输出。但是如果我使用我的 reverseNth 函数,我只会得到列表中的第一件事。 ReverseNth 按部分反转列表。 例如,如果我有一个列表 = 。调用 reverse() 将输出 。在列表中调用 reverseNth(2) 应该给出 。

相关代码:

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

反转第N个代码:

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

【问题讨论】:

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


    【解决方案1】:

    您没有在反向函数中使用startPointendPoint。目前,您的 reverse 函数会反转整个列表,让旧的 head-&gt;next 指向 null(因为它现在是结尾)。

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

    【讨论】:

    • 我改变了我的反向,以便我引用 startPoint 和 endPoint 而不是 head 和 tail。现在我遇到了段错误?我将我的代码编辑为我所拥有的。
    • 好吧,对于初学者来说,您的 p 实际上指向末尾。而while(p!=NULL) 仍然会走到列表的末尾。
    • 所以,我改变了 while 循环,所以它是正确的。但我对你对 p 问题的意思感到困惑?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2016-06-11
    • 2021-04-01
    相关资源
    最近更新 更多