My Avatar

Shilong ZHAO

[s 99] p02 penultimate element in list

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

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

Find the last but one element of a list.

Example:
scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5
def penultimate[T](list: List[T]): Option[T] = if (list.size < 2) None else Some(list(list.size - 2))
penultimate(List(1,2,3,4,5))
penultimate(Nil)
penultimate(List(1))
penultimate(List(1,2))
def penultimateByReverse[T](list: List[T]): Option[T] = if (list.size < 2) None else Some(list.reverse.drop(1).head)
penultimateByReverse(List(1,2,3,4,5))
penultimateByReverse(Nil)
penultimateByReverse(List(1))
penultimateByReverse(List(1,2))