Scala练习题02:列表中找出倒数第二个元素

时间:2021-01-29 10:48:43
//Find the last but one element of a list.
//List列表中找出倒数第二个元素
package com.yl.problem

object Pro02 {

  //01、内置方法解决
  def method01[A](ls: List[A]): A = {
    if (ls.isEmpty) throw new NoSuchElementException
    //init: 返回List[A],除了最后一个元素的所有元素构成的列表,然后.last即为所求元素
    else ls.init.last 
  }


  //02、模式匹配解决
  def method02[A](ls: List[A]): A = ls match{
    case h :: _ :: Nil => h                   //若是两个元素的List 则返回h
    case _ :: tail     => method02(tail)     //后续列表tail继续循环执行至剩余两个元素的列表时(即case h...)
    case _             => throw new NoSuchElementException
  }

  //03、稍作修改内置方法解决
  def method03[A](n: Int, ls: List[A]): A = {
    if (n <= 0) throw new IllegalArgumentException
    if (ls.length < n) throw new NoSuchElementException
    ls.takeRight(n).head //右边的n个元素的列表中的首元素,即倒数第二个则将n赋予2即可
  }

  //04、不用内置方法解决
    def method04[A](n: Int, ls: List[A]): A = {
    def lastNthR(count: Int, resultList: List[A], curList: List[A]): A =
      curList match {
        case Nil if count > 0 => throw new NoSuchElementException
        case Nil              => resultList.head
        case _ :: tail        =>
          lastNthR(count - 1,
                   if (count > 0) resultList else resultList.tail,
                   tail)
      }
    if (n <= 0) throw new IllegalArgumentException
    else lastNthR(n, ls, ls)
  }

  def main(args: Array[String]){
  val list = List(1,8,7,8,3,5,7)  

  println("01内置方法 : " + method01(list))
  println("02模式匹配 : " + method02(list))
  println("03修改内置方法 :" + method03(2, list)) //将n赋予2
  println("04不用内置方法 :" + method04(2, list)) //将n赋予2

  }
}

运行结果:

01内置方法 : 5
02模式匹配 : 5
03修改内置方法 :5
04不用内置方法 :5