这是我反转链表的代码。我接收方法中的根节点,并使用三个指针节点作为上一个、当前和下一个节点。
我的代码颠倒了列表本身,但我想将"根"节点重新分配到列表的末尾,因为它的方向相反,所以我将其分配给了当前节点。
但我注意到,"当前"节点一退出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;
}
你可以试试这个,你在最后给出了错误的根值:
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;
}