1. package com.zhb.corejava.util;  
  2. public class Stack<E> {  
  3.     private E[] elementData;  
  4.     private int top;  
  5.       
  6.     private int count;  
  7.       
  8.     @SuppressWarnings("unchecked")  
  9.     public Stack(int size) {  
  10.         this.elementData = (E[]) new Object[size];  
  11.         top = -1;  
  12.         count = 0;  
  13.     }  
  14.     public Stack() {  
  15.         this(10);  
  16.     }  
  17.       
  18.     /** 
  19.      * 返回堆栈长度 
  20.      * @return 
  21.      */  
  22.     public int getSize(){  
  23.         return elementData.length;  
  24.     }  
  25.       
  26.     /** 
  27.      * 返回栈中元素的个数 
  28.      * @return 
  29.      */  
  30.     public int getElementCount() {  
  31.         return count;  
  32.     }  
  33.       
  34.     /** 
  35.      * 判栈空 
  36.      * @return 
  37.      */  
  38.     public boolean isEmpty(){  
  39.         return top == -1;  
  40.     }  
  41.       
  42.     /** 
  43.      * 判栈满 
  44.      * @return 
  45.      */  
  46.     public boolean isFull(){  
  47.         return top == (elementData.length-1);  
  48.     }  
  49.       
  50.     /** 
  51.      * 入栈操作 
  52.      * @param object 
  53.      */  
  54.     public void push(E object){  
  55.         if(isFull()){  
  56.             throw new RuntimeException("栈已经满");  
  57.         }else{  
  58.             elementData[++top] = object;  
  59.             count++;  
  60.         }  
  61.     }  
  62.       
  63.     /** 
  64.      * 出栈操作,并返回被出栈的元素 
  65.      * @return 
  66.      */  
  67.     public E pop(){  
  68.         if(isEmpty()){  
  69.             throw new RuntimeException("栈是空的");  
  70.         }else{  
  71.             count--;  
  72.             return elementData[top--];  
  73.         }  
  74.     }  
  75. /** 
  76.      * 返回栈顶元素 
  77.      * @return 
  78.      */  
  79.     public E peek(){  
  80.         if(isEmpty()){  
  81.             throw new RuntimeException("栈是空的");  
  82.         }else{  
  83.             return elementData[top];  
  84.         }  
  85.     }  
  86. }
posted @ 2015-04-14 22:50  win24  阅读(107)  评论(0编辑  收藏  举报