棧因爲是臨時存儲,因此一般大小很小java
StackX類方法:數組
構造方法根據參數規定的容量建立一個新棧,棧的域包括表示最大容量的變量。數組自己以及變量top,他存儲棧頂元素的下標。code
push()方法:get
將top自增一,使它指向原頂端數據項上面的一個位置。並在這個位置上存儲一個數據項。再次提醒,top是插入數據項以前遞增的。input
pop()方法:io
返回top標識的數據項值,而後top減一。class
class StackX { private int maxSize; private long[] stackArray; private int top; public StackX(int s) { maxSize = s; stackArray = new long[maxSize]; top = -1; } public void push(long j) { stackArray[++top] = j; } public long pop() { return stackArray[top--]; } public long peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize-1); } } class StackApp { public static void main(String[] args) { StackX theStack = new StackX(10); theStack.push(10); theStack.push(20); theStack.push(30); theStack.push(40); while(!theStack.isEmpty()) { long value = theStack.pop(); System.out.print(value); System.out.print(" "); } System.out.println("end"); } }
40 30 20 10 end
單詞逆序:import
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class StackX1 { private int maxSize; private long[] stackArray; private int top; public StackX1(int s) { maxSize = s; stackArray = new long[maxSize]; top = -1; } public void push(long j) { stackArray[++top] = j; } public long pop() { return stackArray[top--]; } public long peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize-1); } } class Reverser { private String input; private String output; public Reverser(String in) { input = in; } public String doRev() { int StackSize = input.length(); StackX1 theStack = new StackX1(StackSize); for(int j=0;j<input.length();j++) { char ch = input.charAt(j); theStack.push(ch); } output = " "; while(!theStack.isEmpty()) { char ch = (char) theStack.pop(); output = output + ch; } return output; } } class ReverseApp { public static void main(String[] args) throws IOException { String input,output; while(true) { System.out.print("enter"); System.out.flush(); input = getString(); if(input.equals(" ")) break; Reverser theReverser = new Reverser(input); output = theReverser.doRev(); System.out.println(output); } } private static String getString() throws IOException{ // TODO Auto-generated method stub InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); return s; } }
enter kdjfklajkfaj jafkjalkfjdk enter klda;kflakf;kfa afk;fkalfk;adlk enter