[英]Reverse linked list in java
I would like to know if this is a valid recursive solution and if any improvements can be made.我想知道这是否是一个有效的递归解决方案,以及是否可以进行任何改进。 I've tested this solution with a few inputs and it seems to work.我已经用一些输入测试了这个解决方案,它似乎有效。
public Node reverse(Node head) {
if(head == null) {
return null;
}
if (head.next == null) {
this.head = head;
return head;
}
Node n = head.next;
head.next = null;
reverse(n).next = head;
return head;
}
Thank you.谢谢你。
In terms of algorithm, I think this method does what you want, I believe you wanted a linked list在算法方面,我认为这种方法可以满足您的需求,我相信您想要一个链表
A->B->C A->B->C
to be converted to要转换为
C->B->A, and return A. C->B->A,返回A。
I am just a little confused with the scope of this method, is it a instance method of Node?我只是对这个方法的范围有点困惑,它是Node的实例方法吗? what "this" is at line 8.第 8 行的“this”是什么。
One thing I am not sure is, if you do not keep other pointers to C and B, after the reverse is done, then you are left with the list C->B->A, with a returned pointer to A. It looks like C and B are not pointed by any variables, won't it be garbage collected?我不确定的一件事是,如果您不保留指向 C 和 B 的其他指针,在完成反向操作后,您将剩下列表 C->B->A,并返回指向 A 的指针。看起来像 C 和 B 没有被任何变量指向,它不会被垃圾收集吗? and removed?并删除? Maybe this problem is solved by the "this" thing.也许这个问题是通过“这个”的东西来解决的。
A good practice of constructing a list should be a method that return the head of a list.构建列表的一个好习惯应该是返回列表头部的方法。 But your method returns the tail.但是您的方法返回尾部。 I suggest make this an instance method of Node, then you make the reverse() method to be called with head, and return the new head我建议把它作为Node的实例方法,然后用head调用reverse()方法,并返回新的head
public Node reverse() {
if (this.next == null) {
return this;
}
Node n = this.next;
Node newhead=n.reverse() // After reverse, n should be at the tail
n.next = this;
return newhead;
}
something like this, but I have not tested the code像这样,但我还没有测试过代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.