一、以数组为内核的栈的实现:
1 package data.struct.algorithm; 2 3 class Stackx { 4 private int maxSize; 5 private int[] stackArray; 6 private int top; 7 8 //自己的错误出现在这个地方,错误写法:the.maxSize=maxSize; 9 public Stackx(int s) { 10 maxSize = s; 11 stackArray = new int[maxSize]; 12 top = -1; 13 } 14 15 public void push(int j) { 16 stackArray[++top] = j; 17 } 18 19 public int pop() { 20 return stackArray[top--]; 21 } 22 23 public int peek() { 24 return stackArray[top]; 25 } 26 27 public boolean isEmpty() { 28 return top==-1; 29 } 30 31 public boolean isFull() { 32 return top==maxSize-1; 33 } 34 } 35 36 public class StackApp { 37 38 /** 39 * @param args 40 */ 41 public static void main(String[] args) { 42 43 Stackx theStackx = new Stackx(10); 44 theStackx.push(20); 45 theStackx.push(40); 46 theStackx.push(60); 47 theStackx.push(80); 48 theStackx.push(1); 49 theStackx.push(67); 50 theStackx.push(78); 51 theStackx.push(23); 52 System.out.println(theStackx.peek()); 53 while (!theStackx.isEmpty()) { 54 System.out.print(theStackx.pop()+" "); 55 } 56 System.out.println(); 57 } 58 59 }
时间: 2024-10-21 22:20:52