数据结构——栈的实现(数组、Java)

巩固数据结构 栈是一种有限制的线性表 只能对表尾进行操作 

package com.shine.test.datastruct;

import java.util.Arrays;

public class ArrayStack<E> {
	private E top;
	private int initSize = 10;
	private int increment = 10;
	private int size ;
	private Object[] array;
	private int capacity;
	
	public ArrayStack() {
		array = new Object[initSize];
		capacity = initSize;
		top = (E)array[0];
		size = 0;
	}
	
	public boolean isEmpty() {
		if(size == 0) {
			return true;
		}
		return false;
	}
	
	public void add(E e) {
		if(size > capacity/2) {
			capacity = capacity + increment;
			array = Arrays.copyOf(array, capacity);
			System.out.println("----"+size);
		}
		top = e;
		array[size] = top;
		size ++;
	}
	
	public E push() {
		if(size <= 0) { // 如果数组为空返回null
			return null;
		}
		E temp =	top; // 暂存返回值
		top = null; 
		size --;
		if(size >= 1) {
			top = (E)array[size-1];
			return temp;
		}else {
			top = null;
			return temp;
		}
		
	}
	
	public E peek() {
		return top;
	}
	
	public int size() {
		return size;
	}
	
	public int capacity() {
		return capacity;
	}	
	
}

  

原文地址:https://www.cnblogs.com/lihuiupupup/p/8811142.html