前言

在Scala中,List是一个高效的数据结构,尤其对于很多递归算法尤其重要。它可以容易在头部添加元素,也可以得到列表的尾部。

列表的最后一个元素


In [1]:
val list1 = List(1, 1, 2, 3, 5, 8)


list1: List[Int] = List(1, 1, 2, 3, 5, 8)

In [4]:
def lastBuildin[A](ls: List[A]): A = ls.last


defined function lastBuildin

In [5]:
def lastRecursive[A](ls: List[A]): A = ls match {
    case h :: Nil => h
    case _ :: tail => lastRecursive(tail)
    case _ => throw new NoSuchElementException
}


defined function lastRecursive

In [6]:
lastBuildin(list1)


res3: Int = 8

In [7]:
lastRecursive(list1)


res4: Int = 8

列表的倒数第二个元素


In [8]:
def penultimateBuildin[A](ls: List[A]): A =
    if(ls.isEmpty) throw new NoSuchElementException
    else ls.init.last


defined function penultimateBuildin

In [9]:
def penultimateRecursive[A](ls: List[A]): A = ls match {
    case h :: _ :: Nil => h
    case _ :: tail => penultimateRecursive(tail)
    case _ => throw new NoSuchElementException
}


defined function penultimateRecursive

In [10]:
penultimateBuildin(list1)


res7: Int = 5

In [12]:
penultimateRecursive(list1)


res8: Int = 5

In [ ]: