繁体   English   中英

反转单链列表Java

[英]Reversing a singly linked list Java

这是我的反向链接列表代码。 我采用方法中的根节点,并使用三个指针节点充当上一个,当前和下一个节点。

我的代码反转了列表本身,但是我想将“根”节点重新分配到列表的末尾,因为它的方向相反,因此我将其分配给了当前节点。

但是我注意到,“当前”节点退出while循环后,其值立即变回1(原始根节点的值)。 是否有这样做的原因,我将如何补救?

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Node root = new Node();

    root.data = 1;
    root.next.data = 2;
    root.next.next.data = 3;
    root.next.next.next.data = 4;
    root.next.next.next.next.data = 5;

    Node tmp = reverse(root);

    System.out.println(tmp.data);
}

public static Node reverse(Node root)
{
    if (root == null || root.next == null)
        return root;

    Node previous = null;
    Node current = root;
    Node next = root.next;

    while (next != null)
    {
        current.next = previous;
        previous = current;
        current = next;
    //  System.out.println(current.data);
        next = current.next;
    }

    root = current;

    return root;
}

您可以尝试这样做,最后给root赋予错误的值:

public static Node reverse(Node root){
    if(!root) return root;
    Node previous = null;
    Node current = root;
    while(current){
        Node next = current.next;
        current.next = previous;
        previous = current;
        current = next;
    }
    root = previous;
    return root;
}

暂无
暂无

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

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