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;
}
}

//本篇文章来源于csdn论坛:http://topic.csdn.net/u/20100201/21/8abd9e46-c84c-4ba1-bf28-3a8ed907bd94.html
原文链接http://edu.codepub.com/2009/1003/16063.php
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值