java栈的实现

MyStack.java

[java]  view plain  copy
  1. package lianxi;  
  2.   
  3. public class MyStack {  
  4.     private long[] arr;  
  5.     private int top;  
  6.       
  7.     /** 
  8.      * 默认的构造方法 
  9.      */  
  10.     public MyStack(){  
  11.         arr = new long[10];  
  12.         top = -1;  
  13.     }  
  14.     /** 
  15.      * 自定义栈的大小的构造参数 
  16.      * @param maxsize 
  17.      */  
  18.     public MyStack(int maxsize) {  
  19.         arr = new long[maxsize];  
  20.         top = -1;  
  21.     }  
  22.       
  23.     /** 
  24.      * 添加数据 
  25.      */  
  26.     public void push(long value) {  
  27.         arr[++top] = value;  
  28.     }  
  29.       
  30.     /** 
  31.      * 移除数据 
  32.      */  
  33.     public long pop() {  
  34.         return arr[top--];  
  35.     }  
  36.     /** 
  37.      * 查看数据 
  38.      */  
  39.     public long peek() {  
  40.         return arr[top];  
  41.     }  
  42.     /** 
  43.      * 判断是否为空 
  44.      */  
  45.     public boolean isEmpty() {  
  46.         return top == -1;  
  47.     }  
  48.     /** 
  49.      * 判断是否满了 
  50.      */  
  51.     public boolean isFull() {  
  52.         return top == arr.length - 1;  
  53.     }  
  54. }  
testClass.java

[java]  view plain  copy
  1. package lianxi;  
  2. import java.io.*;  
  3. import java.rmi.RemoteException;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Calendar;  
  6. import java.util.Date;  
  7. import java.util.Random;  
  8.   
  9. import SortP.MyStack;  
  10.   
  11. public class  testClass {  
  12.       
  13.     public static void main(String args[]){  
  14.         MyStack ms = new MyStack(4);  
  15.         ms.push(23);  
  16.         ms.push(12);  
  17.         ms.push(1);  
  18.         ms.push(90);  
  19.         System.out.println(ms.isEmpty());  
  20.         System.out.println(ms.isFull());  
  21.           
  22.         System.out.println(ms.peek());//查看栈顶元素  
  23.           
  24.           
  25.         while(!ms.isEmpty()) {  
  26.             System.out.println(ms.pop() + ",");//移除数据  
  27.         }  
  28.           
  29.         System.out.println(ms.isEmpty());  
  30.         System.out.println(ms.isFull());  
  31.           
  32.     }  
  33.       
  34. }  
输出结果:


[java]  view plain  copy
  1. false  
  2. true  
  3. 90  
  4. 90,  
  5. 1,  
  6. 12,  
  7. 23,  
  8. true  
  9. false  

猜你喜欢

转载自blog.csdn.net/sinat_34089391/article/details/80286128