c++ - 反转链表 - C++

标签 c++ function pointers

我写了一个函数来反转列表。

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

An access violation (segmentation fault) raised in your program.

这是我的第一个链表作业,所以我还在学习。

这是我用 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;
    }
}

最佳答案

您的代码已关闭,它正在提前返回。

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

关于c++ - 反转链表 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897302/

相关文章:

c++ - 通过引用而不是通过值从函数中获取对象

arrays - 在谈论字符指针数组时,char *[] 和 char ** 之间的关系是什么

c++ - 使用引用而不是指针有哪些缺点?

c++ - c++中删除变量的详细信息

c++ - Qt窗口框架设计

c++ - 隐式转换运算符 vs 模板构造函数——应该优先考虑谁?

C++ - 指向成员函数的多态指针

c - 从函数传回数组(C 编程)

c++ - 简单的数字猜谜游戏。 C++

c++ - LNK1120 关于使用 lineSetAppPriorityW