Java 栈(Stack)的数据实现方式

栏目: Java · 发布时间: 6年前

public class StackOfArray<E> implements Iterable<E> {

	private E[] item = (E[]) new Object[16];
	private int N = 0;

	private void reSize(int max) {
		E[] temp = (E[]) new Object[max];
		for (int i = 0; i < N; i++) {
			temp[i] = item[i];
		}
		item = temp;
	}

	private void push(E t) {
		if (item.length == N) {
			reSize(2 * item.length);
		}
		item[N++] = t;

	}

	private E pop() {
		E t = item[--N];
		item[N] = null;
		if (N > 0 && N == item.length / 4)
			reSize(item.length / 2);
		return t;
	}

	private E peek() {
		int i = N;
		return item[--i];
	}

	private boolean isEmpty() {
		return N == 0;
	}

	private int size() {
		return N;
	}

	@Override
	public Iterator<E> iterator() {

		return new ArrayIterator();
	}

	class ArrayIterator implements Iterator<E> {
		int i = N;

		@Override
		public boolean hasNext() {

			return i > 0;
		}

		@Override
		public E next() {
			return item[--i];
		}

	}

	public static void main(String[] args) {
		StackOfArray<String> stact = new StackOfArray<>();
		stact.push("A");
		stact.push("W");
		stact.push("E");
		stact.push("R");
		System.out.println(stact.peek());
		System.out.println(stact.pop());
		System.out.println("" + stact.isEmpty());
		System.out.println("" + stact.size());
		Iterator<String> it = stact.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

}

复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器