【发布时间】: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