題目:編寫程序,按升序?qū)_M(jìn)行排序(即最大元素位于棧頂).最多只能使用一個額外的棧存放臨時數(shù)據(jù)。
核心代碼:
<pre><code>` func sort(data:[Int])->[Int] {
var stack:[Int] = data
var nextStack:[Int] = []
while stack.count > 0 {
let top:Int = stack.last!
stack.removeLast() // 移除
while nextStack.count > 0 && nextStack.last! > top {
stack.append(nextStack.last!)
nextStack.removeLast()
}
nextStack.append(top)
}
return nextStack
}`</code></pre>
測試代碼:
<pre><code>var stackSort:StackSort = StackSort() var sortData:[Int] = stackSort.sort(data: [8,5,4,3,10,1,7,9,2,6]) print("FlyElephant---排序之后的數(shù)據(jù)---\(sortData)")</code></pre>

FlyElephant.png