【问题标题】:Reversing a singly linked list Java反转单链表Java
【发布时间】:2014-10-23 01:42:17
【问题描述】:

这是我用于反转链表的代码。我在方法中获取根节点,并使用三个指针节点作为前一个节点、当前节点和下一个节点。

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

但我注意到,“当前”节点在退出 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;
}

【问题讨论】:

    标签: java linked-list


    【解决方案1】:

    你可以试试这个,最后你给了错误的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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 2014-12-30
      • 2016-06-07
      相关资源
      最近更新 更多