public class Stack {
目前创新互联已为1000+的企业提供了网站建设、域名、雅安服务器托管、网站托管、服务器租用、企业网站设计、中卫网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
private Object[] stack;
//这个不需要;
//private int top = 0; //初始化栈顶
//这个也不需要;
//写一个栈出来,最好是可以动态的,可以自己改变大小的,即数组的长度;
//private int size = 0; // 初始化大小
//元素个数;
private int size;
//默认长度为10;
public Stack(){
this(10);
}
//也可以自己设置长度,即容量;
public Stack(int len){
stack = new Object[len];
}
//返回元素个数;
public int size(){
return size;
}
//返回数组长度,即容量;
public int capacity(){
return stack.length;
}
//实现动态的数组;
public void ensureCapacity(){
if(size() == capacity()){
Object[] newStack = new Object[size() * 3 / 2 + 1];
System.arraycopy(stack, 0, newStack, 0, size());
stack = newStack;
}
}
//入栈;
public void push(Object o){
size++;
ensureCapacity();
stack[size - 1] = o;
}
/*
public void push(Object object) {
if (isFull()) {
System.out.println("栈满! 入栈失败");
}
stack[top++] = object;
}
*/
//判空;
public boolean isEmpty(){
return size == 0;
}
//出栈;
public Object pop(){
//首先要判空;
if(isEmpty()){
throw new ArrayIndexOutOfBoundsException("不能为空");
}
Object o = stack[--size];
stack[size] = null;
return o;
}
/*
// 出栈
public Object pop() {
Object object = stack[--top];
stack[top] = null;
return object;
}
*/
/*
// 计算栈当前大小
public int size() {
return top;
}
// 判断是否是空栈
public boolean isEmpey() {
return top == 0;
}
// 判断是否栈满
public boolean isFull() {
return top = size;
}
public Stack(int size) {
this.size = size;
}
*/
public static void main(String[] args) {
Stack stack = new Stack(3);
String[] data = new String[] { "a", "b", "c" };
for (int i = 0; i data.length; i++) {
stack.push(data[i]);
System.out.println(data[i] + "");
}
System.out.println("***********");
while (!stack.isEmpty()) {
System.out.println(stack.pop() + "");
}
//}
}
}
你自己对比一下,我是在你的里面修改的
Java堆栈类Junit测试源代码
import java.util.LinkedList;
import java.io.*;
import java.util.NoSuchElementException;
/**
*
* @version 1.00 06/12/19
*/
public class MStack
{
LinkedList list;
public MStack()
{
list=new LinkedList();
}
public static void main(String[] args)
{
MStack MStack=new MStack();
MStack.push("ok");
MStack.push("i am ok");
System.out.println(MStack.pop());
System.out.println(MStack.pop());
System.out.println(MStack.pop());
}
//弹出元素
public Object pop()
{
try
{
Object o=list.getFirst();
list.removeFirst();
return o;
}
catch(NoSuchElementException e)
{
//System.out.println(e);
return null;
}
}
//压入元素
public void push(Object o)
{
list.addFirst(o);
}
//得到栈顶元素
public Object getTop()
{
if(list.size()!=0)
{
return list.getFirst();
}
else
{
return null;
}
}
}
参看: 1 import java.util.*; 2 3 public class TestStack { 4 public static void main(String[] args) { 5 Stack stack = new Stack(); 6 7 for(int i = 0; i 10; i++) { 8 stack.push(new Integer(i)); 9 }1011 if(!stack.empty()) {12 System.out.println(stack.pop());13 }14 }15 }