java实现一个栈

来源:互联网 发布:软件光盘品牌 编辑:程序博客网 时间:2024/05/17 09:02

实现一个栈

栈是一个比较常用的数据结构 无论面试还是算法比赛
follow me progress step by step:

  • 初始化
  • 入栈
  • 出栈
  • 获取栈顶
  • *判空
  • 获取栈内元素个数/栈的大小
  • 动态变长
  • 用泛型使得代码变得适用性更强
  • 异常处理

以下为具体实现代码

分为两个类 一个栈的实现类 一个测试类

Stack.java

package arithmetic;
import java.util.Arrays;
/**
* what’s stack
* implements
* @author Administrator
*
*/
public class Stack {
private int size=0;
private Object[] array;
/**
* 默认初始化 默认构造方法
*/
public Stack(){
this(10);
}
/**
* 带参数构造方法
* @param i
*/
public Stack(int initialCapacity) {
if(initialCapacity<=0){
throw new RuntimeException(“初始化栈空间错误”);
}
array=new Object[initialCapacity];
}

/** * 入栈 */public E push(E item){    ensureCapacityHelper(size+1);    array[size++]=item;    return item;}/** * 获取栈顶元素 */public E peek(){    if(isEmpty()){        throw new IndexOutOfBoundsException("栈已经空");    }    return (E) array[size-1];}/** * 出栈  获取栈顶元素 */public E pop(){    E item=peek();    size--;    return item;}/** * 判空 */private boolean isEmpty() {    return size==0;}/** * 确保空间够用 */private void ensureCapacityHelper(int minCapacity) {    if(minCapacity>array.length){        //调用方法 扩容        grow();    }}/** * 动态扩容 */private void grow(){    int oldCapacity=array.length;    int newCapacity=oldCapacity*2;    if(newCapacity<oldCapacity){        throw new OutOfMemoryError();    }else{        array=Arrays.copyOf(array,newCapacity);    }}

}

test.java

package arithmetic;

public class test {

public static void main(String[] args) {    Stack<String> s=new Stack<String>();    s.push("abc");    s.push("bcde");    System.out.println(s.pop());    System.out.println(s.peek());}

}

1 0
原创粉丝点击