简体   繁体   English

链表反向不起作用……?

[英]linked list reverse is not working …?

I know it is a minute code. 我知道这是分钟代码。 I can't understand why my linked list reversal is not working. 我不明白为什么我的链表反转无法正常工作。 Can some one help fix me my reverse method in the below code. 可以在下面的代码中帮助我解决反向方法吗?

//Reverse a single linked list
public Node reverse()
{
    return reverse(root);
}
private Node reverse(Node node)
{
        Node previous = null;  
        Node current = node;  
        Node forward;  

        while (current != null) 
    {  
            forward = current.next;  
            current.next = previous;  
            previous = current;  
            current = forward;  
        }  
    return previous;  
}

Any input on this would be helpful 任何对此的投入将是有帮助的

Thanks !!! 谢谢 !!!

Assuming homework... 假设功课...

Write simple tests: list of 0 items, list of 1 items, list of 2 items, list of 10 items. 编写简单的测试:0项列表,1项列表,2项列表,10项列表。 Than make sure each of them work - will narrow down error and learn to write unit tests. 比确保每个工具都能正常工作-可以缩小错误范围并学习编写单元测试。

您确定使用返回值的reverse()而不是root进行迭代吗?

I'm pretty sure it should be 我很确定

return root = reverse(root);

(Your reverse logic is correct, but if the root is still pointing at the old root of the list, you will end up with a 1-element linked list.) (您的反向逻辑是正确的,但是如果root仍然指向列表的旧根,则最终将得到一个1元素的链接列表。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM