码迷,mamicode.com
首页 > 编程语言 > 详细

用数组写出栈(先进后出)

时间:2015-05-28 21:38:59      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

<pre name="code" class="java">//用数组写出栈(先进后出)


import java.util.Collection; import java.util.NoSuchElementException; public class ArrayStack<E> { private int initalSize = 5; private Object[] stack; private int head; private int tail; public ArrayStack() { initialize(null); } public ArrayStack(int newcapacity){ if (newcapacity < this.initalSize) throw new IllegalArgumentException("The new capacity is too small!"); initalSize = newcapacity; initialize(null); } public ArrayStack(E[] items) { initialize(items); } public ArrayStack(Collection<E> collection) { initialize(collection.toArray()); } private void initialize(Object[] items){ if (items == null || items.length == 0){ stack = new Object[initalSize]; head = 0; tail = 0; } else{ stack = new Object[items.length + 1]; System.arraycopy(items, 0, stack, 0, items.length); head = items.length; tail = 0; } } @SuppressWarnings("unchecked") public E pop(){ if (size() == 0) throw new NoSuchElementException(); if (head == 0) head = stack.length; Object ret = stack[--head]; loseWeight(); return (E)ret; } public void push(E item){ increaseWeight(); stack[head++] = item; if (head == stack.length) head = 0; } @SuppressWarnings("unchecked") public E peek(){ if (size() == 0) throw new NoSuchElementException(); if (head == 0) return (E)stack[stack.length - 1]; else return (E)stack[head-1]; } public boolean isEmpty(){ return (size() == 0); } public int size(){ return head >= tail ? head - tail : head + stack.length - tail; } public boolean increaseWeight(){ if (size() == stack.length - 1){ Object[] newStack = new Object[stack.length * 2]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; return true; } return false; } public boolean loseWeight(){ if (size() == stack.length / 4){ Object[] newStack = new Object[stack.length/2]; if (head >= tail){ System.arraycopy(stack, tail, newStack, 0, size()); } else{ System.arraycopy(stack, tail, newStack, 0, stack.length-tail); System.arraycopy(stack, 0, newStack, stack.length-tail, head); } tail = 0; head = size(); return true; } return false; } }


用数组写出栈(先进后出)

标签:

原文地址:http://blog.csdn.net/s2940086379/article/details/46127551

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!