Last active
August 29, 2015 14:02
-
-
Save rgantt/bcc7a35c8774f878e3a0 to your computer and use it in GitHub Desktop.
Musings in generic list reversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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