反向链表- c++

Reversing Linked List - C++

本文关键字:c++ 链表      更新时间:2023-10-16

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

到目前为止,我只能逆转两个项目,但没有更多。我检查了又检查,仍然找不到问题所在。我甚至使用调试器来查看每个指针的值。当运行调试器时,我收到消息:

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

这是我第一次使用链表,所以我还在学习中。

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

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

我认为向这些人展示当列表被反转时,列表的状态会发生什么变化会更有帮助。这应该比向他们展示代码或代码问题更能帮助他们。

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

[] = head() = current

([1]) -> 2 -> 3 -> 4,[2] -> (1) -> 3 -> 4,[3] -> 2 -> (1) -> 4,[4]->3->2->(1)完成了,因为现在没有新的next

很抱歉回复晚了,我相信你现在已经找到了答案,但它可能对其他人有帮助。答案是简单地采取返回语句(即返回头;)while循环将解决你的问题。尽管有一些方法可以避免额外的指针和赋值来优化代码。