要求:
一個棧依次壓入1,2,3,4,5那麼從棧頂到棧底分別為5,4,3,2,1。將這個棧轉置後,從棧頂到棧底為1,2,3,4,5,也就是實現棧中元素的逆序,但是隻能用遞迴函式來實現,而不能用另外的資料結構。
import java.util.Stack; public class Problem03_ReverseStackUsingRecursive { /* * 遞迴得到棧底元素 */ public static int getAndRemoveLastElement(Stack<Integer> stack){ int result = stack.pop(); if (stack.isEmpty()){ return result; } else { int lastElement = getAndRemoveLastElement(stack); stack.push(result); return lastElement; } } /* * 逆序 */ public static void reverse(Stack<Integer> stack) { if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack); reverse(stack); stack.push(i); } public static void main(String[] args) { Stack<Integer> test = new Stack<Integer>(); test.push(1); test.push(2); test.push(3); test.push(4); test.push(5); System.out.println(test); reverse(test);
System.out.println(test);
while (!test.isEmpty()) { System.out.println(test.pop()); } } }
執行結果:
[1, 2, 3, 4, 5] [5, 4, 3, 2, 1] 1 2 3 4 5