欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java实现 栈

程序员文章站 2024-01-24 11:13:28
...
package date0609;

/**
 *@author TonyJ
 *@time 2011-6-9 下午03:18:00
 */
public class Test01 {
	private long arr[];
	private long temparr[];
	private int maxSize;//栈的最大容量
	private int top;//栈顶标志

	public Test01(int s) {
		maxSize = s;
		arr = new long[s];
		top = -1;
	}

	public void push(long data) {//数据入栈
		if (top < maxSize-1) {
			arr[++top] = data;
		} else {//扩容栈空间
			maxSize = maxSize * 2;
			temparr = new long[maxSize];
			System.arraycopy(arr, 0, temparr, 0, maxSize/2);
			arr=temparr;
			arr[++top] = data;
		}
	}

	public long pull() {//数据出栈
		return arr[top--];
	}

	public long peek() {//取得栈顶元素
		return arr[top];
	}

	public boolean isEmpty() {//判断是栈否为空
		return top == -1;
	}

	public boolean isFull() {//判断栈是否已满
		return top == maxSize - 1;
	}

	public static void main(String[] args) {
		Test01 t = new Test01(4);
		t.push(1);
		t.push(2);
		t.push(3);
		t.push(4);
		t.push(5);
		t.pull();
		while(!t.isEmpty()){
			System.out.print(t.pull()+",");
		}
	}
}

相关标签: Java