[英]Is this a correct way to reverse a singly linked list?
This is the code that I came up with to reverse a singly-linked-list in Java and I am wondering whether it is correctly done.这是我想出的用于反转 Java 中的单链表的代码,我想知道它是否正确完成。 I know that it works as far as doing its job and having the run time of O(n), but is this a right way to do it or what can be improved?
我知道它就其工作和 O(n) 的运行时间而言是有效的,但这是一种正确的方法还是可以改进的地方? Also what can I do to avoid a stack-overflow problem when reversing a long linked list (without using an iterative alternative), because when trying to reverse a linked list of size greater than 8300, it causes a stack-overflow exception.
另外,在反转长链接列表(不使用迭代替代方案)时,我可以做些什么来避免堆栈溢出问题,因为当尝试反转大小大于 8300 的链接列表时,它会导致堆栈溢出异常。
private void reverse(Node node) {
if(node != this.tail) {
reverse(node.next);
this.tail.next = new Node(node.item);
this.tail = this.tail.next;
this.head = this.head.next;
}
}
public void reverse() {
reverse(this.head);
}
That solution seems fine, however you do not need to create new Node
objects with the values from old Node
objects.该解决方案看起来不错,但是您不需要使用旧
Node
对象的值创建新的Node
对象。 You can reverse a singly-linked-list in-place and in O(n)
time complexity.您可以在
O(n)
时间复杂度内就地反转单链表。
public Node reverse(Node head) {
Node prev = null;
while(head!= null) {
Node rem = head.next;
head.next = prev;
prev = current;
current = rem;
}
return prev; // prev is the new head of your linked list
}
If you do not want to use an iterative solution (although I'd recommend to do so), you can use recursive solution below:如果您不想使用迭代解决方案(尽管我建议这样做),您可以使用下面的递归解决方案:
public Node reverseList(Node node) { // send the head of the list
if(current == null) return null;
reverse(current);
return this.tail; // now tail is the head and head is the tail
}
public Node reverse(Node node) {
if(node.next == null) {
this.tail = node;
} else {
reverse(node.next).next = node;
node.next = null;
}
return node;
}
I don't have enough details about your linked list, but I assume you have this.head
and this.tail
fields.我没有关于您的链接列表的足够详细信息,但我假设您有
this.head
和this.tail
字段。 This solution works even if this.tail
is not initialized.即使未初始化
this.tail
,此解决方案也有效。 Moreover, if it is assigned beforehand, you don't need to iterate through the linked list from beginning.此外,如果它是预先分配的,则不需要从头开始遍历链表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.