My Avatar

Shilong ZHAO

[s 99] p05 reverse a list

2020-06-22 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Reverse a list.

Example:

scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)
def reverse[T](a: List[T]): List[T] = a.reverse

def reverse2[T](a: List[T]): List[T] = a match {
    case Nil => Nil
    case x::xs => reverse2(xs) :+ x
}

def reverse3[T](a: List[T]): List[T] = a.foldLeft(List[T]())((l, e) => e::l)

val l = List(1,2,3,4)

reverse(l)
reverse(Nil)

reverse2(l)
reverse2(Nil)

reverse3(l)
reverse3(Nil)