'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. 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? 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.
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
