算法(第四版)之 --栈

栈:是一种基于后进先出(LIFO)策略的集合类型
用数组实现栈:

public class Stack<Item>{
	pirvate int n=0;
	private Item []data=new Item[1];
	public boolean isEmpty(){
		return n==0;
	};
	public int size(){
		return n;
	};
	
	public void reSize(int max){
		Item []a=new Item[max];
		for(int i=0;i<data.length;i++){
		a[i]=data[i];
		}
		data=a;
	};
	public void push(Item item){
		if(n==data.length){
			reSize(2*data.length);
		}
		data[n++]=item;
	};
	public Item pop(){
		Item item=data[n--];
		a[n]=null;
		if(n>0&&n=data.length/4){
			reSize(data.length/2);
		}
		return item
	};
}

链表实现栈:

public class Stack<Item>{
	private int n;
	private Node first;
	class Node{
		Item item;
		Node next;
	}
	public boolean isEmpty(){
		return n==0;
	};
	public int size(){
		return n;
	};
	public void push(){
		Node node=first;
		first=new Node();
		first.next=node;
		first.item=Item;
		n++;
	}
	public Item pop(){
		Item item=first.item;
		first=first.next;
		n--;
		return item;
	}
}
上一篇:模型训练过程中loss出现nan的原因


下一篇:【CF3C Tic-tac-toe】题解