The first solution uses recursion.
Node reverseList(Node previous, Node current) {
Node tmp;
if (current.next == null) {
current.next = previous;
return current;
}
tmp = reverseList(current, current.next);
current.next = previous;
return tmp;
}
The second solution is non-recursive.
Node reverse(Node current) {
Node tmp;
Node previous = null;
while (current != null) {
tmp = current.next;
current.next = previous;
previous = current;
current= tmp;
}
return previous;
}
No comments:
Post a Comment