val testList: List[Int] = List(1, 2, 3, 4, 5)
def swapEvenAndOddElementsRecursively( listToSwap: List[Int]): List[Int] = {
listToSwap match {
// Base Cases (2) Empty list and list with single element
case Nil | _ :: Nil => listToSwap
// Recursive case take 2 elements swap and process rest of list
case firstElement :: secondElement :: rest => secondElement :: firstElement :: swapEvenAndOddElementsRecursively(rest)
}
}
@tailrec
final def swapEvenAndOddElementsWithTailRecursion( listToSwap: List[Int], result: List[Int] = List.empty): List[Int] = {
listToSwap match {
// Base Case (1) Empty list
case Nil => result
// Base Case (2) List with single element
case singleNumber :: Nil => result ::: List(singleNumber)
// Recursive case take 2 elements swap, append to result, and process rest of list
case firstElement :: secondElement :: rest =>
val updatedResult: List[Int] = result ::: List(secondElement, firstElement)
// val updatedResult: List[Int] = (firstElement :: secondElement :: result.reverse).reverse
swapEvenAndOddElementsWithTailRecursion(rest, updatedResult)
}
}
println(swapEvenAndOddElementsRecursively(testList))
// List(2, 1, 4, 3, 5)
println(swapEvenAndOddElementsWithTailRecursion(testList))
// List(2, 1, 4, 3, 5)
2条答案
按热度按时间yvgpqqbh1#
从…开始
grouped()
.9rbhqvlz2#
或者,另一个好的通用方法是模式匹配:
注意,对于尾部递归优化,方法必须声明为final或private(不能重写),并且必须具有线性模式(一个递归案例,任意数量的基本案例)