1 public class Stack { 2 3 public static void main(String args[]) 4 { 5 ArrayTest1 arr = new ArrayTest1(10); 6 7 8 arr.push(8); 9 arr.push(7); 10 arr.push(6); 11 arr.push(5); 12 13 while(!arr.isEmpty()) 14 { 15 System.out.print(arr.pop()+" "); 16 } 17 } 18 } 19 class ArrayTest1 20 { 21 private int maxsize; 22 private long[] a; 23 private int top; 24 25 public ArrayTest1(int maxsize) 26 { 27 this.maxsize = maxsize; 28 a = new long[this.maxsize]; 29 top = -1; 30 } 31 32 public void push(long value) 33 { 34 a[++top] = value; 35 } 36 37 public long pop() 38 { 39 return a[top--]; 40 } 41 42 public boolean isEmpty() 43 { 44 return (top==-1); 45 } 46 47 public boolean isFull() 48 { 49 return (top==maxsize-1); 50 } 51 52 public long peek() 53 { 54 return a[top]; 55 } 56 }
下面的这段代码是字符串倒叙的java实现,采用了栈的数据结构,不输入字符串则自动退出。用JUnit测试完成,按照提示自动导入JUnit包就可以运行。
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 import org.junit.Test; 6 7 public class Reverse { 8 private String input; 9 private String output; 10 public Reverse(String in) 11 { 12 input = in; 13 } 14 15 public String doRev() 16 { 17 int stackSize = input.length(); 18 StackX theStack = new StackX(stackSize); 19 20 for(int j=0;j<input.length();j++) 21 { 22 char ch = input.charAt(j); 23 theStack.push(ch); 24 } 25 output=""; 26 while(!theStack.isEmpty()) 27 { 28 char ch = (char) theStack.pop(); 29 output = output+ch; 30 } 31 return output; 32 } 33 } 34 35 36 class ReverseApp 37 { 38 @Test 39 public static void main(String args[]) throws IOException 40 { 41 String input,output; 42 while(true) 43 { 44 System.out.print("enter a string:"); 45 //flush();是流式输入输出常用的一个方法,表示强制请求清空缓冲区, 46 //让i/o系统立马完成它应该完成的输入、输出动作。 47 System.out.flush(); 48 input = getString(); 49 if(input.equals("")) 50 break; 51 Reverse theReverser = new Reverse(input); 52 output = theReverser.doRev(); 53 System.out.println("Reversed:"+output); 54 } 55 } 56 57 public static String getString() throws IOException 58 { 59 InputStreamReader isr = new InputStreamReader(System.in); 60 BufferedReader br = new BufferedReader(isr); 61 String s = br.readLine(); 62 return s; 63 } 64 65 } 66 67 class StackX1 68 { 69 private int maxsize; 70 private char[] stackArray; 71 private int top; 72 73 public StackX1(int maxsize) 74 { 75 this.maxsize = maxsize; 76 stackArray = new char[this.maxsize]; 77 top = -1; 78 } 79 80 public void push(char a) 81 { 82 stackArray[++top] = a; 83 } 84 85 public char pop() 86 { 87 return stackArray[top--]; 88 } 89 90 public boolean isEmpty() 91 { 92 return (top==-1); 93 } 94 95 public char peek() 96 { 97 return stackArray[top]; 98 } 99 100 public boolean isFull() 101 { 102 return (top==maxsize); 103 } 104 }