/// 取出栈底的数 func getAndRemoveLastElement(_ items: inout [Int]) -> Int { let value = items.remove(at: 0) if (items.isEmpty) { return value } let last = getAndRemoveLastElement(&items) items.insert(value, at: 0) return last } func reverse(_ items: inout [Int]) { if (items.isEmpty) { return } let value = getAndRemoveLastElement(&items) reverse(&items) // 逆序把栈底的数放回数组中,完成逆序 items.append(value) } var data = [1, 2, 3, 4, 5] reverse(&data) print(data)
参考文章: