Skip to content

Instantly share code, notes, and snippets.

@rgantt
Last active August 29, 2015 14:02
Show Gist options
  • Save rgantt/bcc7a35c8774f878e3a0 to your computer and use it in GitHub Desktop.
Save rgantt/bcc7a35c8774f878e3a0 to your computer and use it in GitHub Desktop.
Musings in generic list reversal
public static <A> Node<A> reverse(final Node<A> head) {
Node<A> curr;
Node<A> previous = null;
while (head != null) {
curr = head.next;
head.next = previous;
previous = head;
head = curr;
}
return previous;
}
public static <A> List<A> rev(final List<A> list) {
if (list.isEmpty()) return new LinkedList<A>();
else {
List<A> rev = rev(list.subList(1, list.size()));
rev.add(list.get(0));
return rev;
}
}
def rev[A](list: List[A]): List[A] = list match {
case x :: xs => rev(xs) ::: List(x)
case Nil => Nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment