反转链表 - C ++

时间:2011-10-26 00:07:28

标签: c++ function pointers

我写了一个应该反转列表的函数。

到目前为止,我只能反转两项,但不能再反转。我检查并仔细检查,仍然无法找到问题。我甚至使用调试器来查看每个指针的值。运行调试器时,我收到了消息:

  

程序中出现访问冲突(分段错误)。

这是我第一次使用链表进行分配,所以我还在学习。

这是我在Dev-C ++中编写的代码:

List::ListNode *List::Reverse_List(ListNode *head)
{
    ListNode *cur = head;
    ListNode *forward = NULL;
    ListNode *previous = NULL;

    while (cur != NULL)
    {
        head = cur; //set the head to last node
        forward = head->next;  //save the next pointer in forward
        cur->next = previous;  //change next to previous
        previous = cur;
        cur = forward;

        cout << "cur= " << cur->item << endl; //this is just to display the current value of cur

        return head;
    }
}

3 个答案:

答案 0 :(得分:4)

你的代码很接近,它提前返回。

List::ListNode *List::Reverse_List(ListNode *head) 
{
    ListNode *cur = head;
    ListNode *forward = NULL;
    ListNode *previous = NULL;

    while (cur != NULL) {
        //There is no need to use head here, cur will suffice
        //head = cur; //set the head to last node
        forward = cur->next; //save the next pointer in forward

        cur->next = previous; //change next to previous
        previous = cur;
        cur = forward;

        cout << "cur= " << cur->item << endl; //this is just to display the current value of cur

        //don't return here you have only adjusted one node
        //return head;
    }

    //at this point cur is NULL, but previous still holds the correct node
    return previous;
}

答案 1 :(得分:0)

今天每个人都必须完成相同的家庭作业。

我认为这些人向他们展示在被撤消时列表状态会发生什么更有帮助。这应该比向他们展示代码或代码问题更有帮助。

以下是应该发生的事情(使用我将使用的算法)

[] =头 ()=当前

([1]) - &GT; 2→3→4, [2] - &GT;(1) - 将3-→4, [3] - &GT; 2→(1) - →4, [4] - &gt; 3-&gt; 2-&gt;(1)完成因为现在没有新的下一个

答案 2 :(得分:0)

很抱歉回答迟到,我相信你现在已经找到了答案,但它可能对其他人有帮助。答案只是采取return语句(即返回头;)out while while循环将解决你的问题。虽然有一些方法可以避免额外的指针和分配来优化代码。