栈和队列

public class MyLinkedQueue<AnyType> {

	private Node first = null;
	private Node last = first;
	private int N = 0;
	
	private class Node{
		public AnyType item;
		public Node next;
	}
	
	public boolean isEmpty(){
		return first == last;
	}
	public int size(){
		return N;
	}
	public void enqueue(AnyType item){
		last = new Node();
		last.item = item;
		last.next = null;
		last = last.next;
		N++;
	}
	public AnyType dequeue(){
		if(!isEmpty()){
			AnyType temp = first.item;
			first = first.next;
			N--;
			return temp;
		}
		else return null;
	}
}


public class MyArrayStack<AnyType> implements Iterable<AnyType> {
	
	private AnyType[] stack = null;
	private int N = 0;
	
	//构造器
	public MyArrayStack(){
		stack = (AnyType[])new Object[1];
	}
	public boolean isEmpty(){
		return N == 0;
	}
	public int size(){
		return N;
	}
	public void push(AnyType item){
		if(N == stack.length){
			resize(2*stack.length);
		}
		stack[N++] = item;
	}
	public AnyType pop(){
		AnyType temp = stack[--N];
		stack[N] = null;//出栈对象空引用等待回收
		if(N == stack.length/4){
			resize(stack.length/2);
		}
		return temp;
	}
	public void resize(int max){
		AnyType[] temp = (AnyType[])new Object[max];
		for(int i=0; i<N; i++){
			temp[i] = stack[i];
		}
		stack = temp;
	}
	
	public java.util.Iterator<AnyType> iterator(){
		return new ArrayStackIterator();
	}
	private class ArrayStackIterator implements java.util.Iterator<AnyType>{
		
		private int i=N;
		
		public boolean hasNext(){
			return i > 0;
		}
		
		public AnyType next(){
			return stack[--i];
		}
		
		public void remove(){
			
		}
	}
}

public class MyLinkedStack<AnyType> implements Iterable<AnyType> {

	public Node first;
	public int N = 0;
	
	private class Node{
		public AnyType item;
		public Node next;
	}
	
	public boolean isEmpty(){
		return N == 0;
	}
	public int size(){
		return N;
	}
	public void push(AnyType item){
		Node oldfirst = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		N++;
	}
	public AnyType pop(){
		AnyType temp = first.item;
		first = first.next;
		N--;
		return temp;
	}
	
	public java.util.Iterator<AnyType> iterator(){
		return null;
	}
	
	private class LinkedStackIterator implements java.util.Iterator<AnyType>{
		private Node current = first;
		
		public boolean hasNext(){
			return current != null;
		}
		
		public AnyType next(){
			AnyType temp = current.item;
			current = current.next;
			return temp;
		}
		public void remove(){
			
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值