首页 > 编程语言 > 详细

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

时间:2015-05-28 21:36:24      阅读:307      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!