java数据结构栈

栈的原则是先进后出,比如一堆摞起来的书,后放上去的会被最先拿到。

栈的特点是每次只允许访问一个元素。

栈是一种抽象出来的数据结构,它的底层存储依赖于数组和链表,下面列出它的两种实现

public interface Stack <T>{
	
	boolean isEmpty();
	
	void clear();
	
	int length();
	
	boolean push(T obj);
	
	T pop();
	
	boolean hashNext();
}

public class ArrayStack<T> implements Stack<T> {

	private static final int DEFULT_SIZE = 20;
	
	private static final int STEP_SIZE = 10;
	
	private Object[] objects = new Object[DEFULT_SIZE];
	
	private int size;
	
	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@Override
	public void clear() {
		for (int i = 0; i < size; i++) {
			objects[i] = null;
		}
		size = 0;
	}

	@Override
	public int length() {
		return size;
	}

	@Override
	public boolean push(T obj) {
		resize();
		objects[++size] = obj;
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T pop() {
		if(size == 0){
			return null;
		}
		return (T) objects[--size];
	}

	public void resize() {
		if(size >= objects.length){
			Object[] temp = new Object[objects.length + STEP_SIZE];
			for(int i=0;i<objects.length;i++){
				temp[i] = objects[i];
				objects[i] = null;
			}
			objects = temp;
		}
		
	}

	@Override
	public boolean hashNext() {
		return objects[size - 1] != null;
	}

	public static void main(String[] args) {
		Stack<Integer> linkedStack = new LinkedStack<Integer>();
		linkedStack.push(1);
		linkedStack.push(2);
		linkedStack.push(3);
		linkedStack.push(4);
		linkedStack.push(5);
		while(linkedStack.hashNext()){
			System.out.println(linkedStack.pop());
		}
	}
	
}

public class LinkedStack<T> implements Stack<T>{

	int size = 0;
	
	private Item top;
	
	private final class Item{
		private Item next;
		
		private T data;
		
		private Item(T data,Item next){
			this.data = data;
			this.next = next;
		}
		
		private boolean hasNext(){
			return next != null;
		}
	} 
	
	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@Override
	public void clear() {
		setItemNull(top);
		size = 0;
	}

	@Override
	public int length() {
		return size;
	}

	private void setItemNull(Item item){
		if(item.hasNext()){
			setItemNull(item.next);
		}
		item = null;
	}
	
	@Override
	public boolean push(T obj) {
		Item item = new Item(obj,top);
		top = item;
		size ++;
		return true;
	}

	@Override
	public T pop() {
		if(top != null){
			Item item = top;
			top = item.next;
			size--;
			return item.data;
		}
		return null;
	}

	@Override
	public boolean hashNext() {
		return top != null;
	}
	
	public static void main(String[] args) {
		Stack<Integer> linkedStack = new LinkedStack<Integer>();
		linkedStack.push(1);
		linkedStack.push(2);
		linkedStack.push(3);
		linkedStack.push(4);
		linkedStack.push(5);
		while(linkedStack.hashNext()){
			System.out.println(linkedStack.pop());
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值