1 package structure; 2 3 import static net.mindview.util.Print.*; 4 5 import java.util.Arrays; 6 import java.util.Scanner; 7 8 /** 9 * 栈的两种实现:数组和链表 :arraylist 和 linkedlist 10 * 本例实现的是数组的封装方式 11 * @author Tom Tao 12 * 13 */ 14 15 public class Stack { 16 17 public static int[] num = new int[100]; 18 public static int top = 0; 19 20 /*初始化*/ 21 public static void init(int n[]) { 22 Arrays.fill(num, -1); 23 for(int i = 1 ; n[i] != -1 ; i ++) { 24 num[i] = n[i]; 25 } 26 } 27 28 /*打印*/ 29 public static void printStack() { 30 for(int i = top ; i > 0 ; i --) { 31 printnb(num[i] + " "); 32 } 33 print(); 34 } 35 36 /*入栈*/ 37 public static void insert(int val) { 38 num[++ top] = val; 39 printStack(); 40 } 41 42 /*获取栈顶*/ 43 public static int getTop() { 44 return num[top]; 45 } 46 47 /*出栈*/ 48 public static int pop() { 49 int n = num[top]; 50 num[top --] = -1; 51 return n; 52 } 53 54 /*判断是否为空*/ 55 public static boolean isEmpty() { 56 return top <= 0; 57 } 58 59 /*test*/ 60 public static void main(String[] args) { 61 Scanner sc = new Scanner(System.in); 62 int n[] = new int[100]; 63 Arrays.fill(n, -1); 64 int val; 65 print("please input the nums to init"); 66 while((val = sc.nextInt()) != -1){ 67 n[++ top] = val; 68 } 69 init(n); 70 printStack(); 71 print("please input the num to insert"); 72 val = sc.nextInt(); 73 insert(val); 74 print("get the top"); 75 print(getTop()); 76 print("pop"); 77 print(pop()); 78 printStack(); 79 print("is empty"); 80 print(isEmpty()); 81 sc.close(); 82 } 83 84 }
浙公网安备 33010602011771号