先进先出队列(链表实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dutsoft/article/details/25502055
import java.util.Scanner;
import java.util.Iterator;

// 先进先出队列
public class MyQueue<Item> implements Iterable<Item> {
	private Node first;
	private Node last;
	private int N;
	
	private class Node{
		Item item;
		Node next;
	}
	
	public boolean isEmpty(){
		return first==null;
	}
	public int size(){
		return N;
	}
	
	// 向表尾添加元素
	public void enqueue(Item item){
		Node oldlast=last;
		last=new Node();
		last.item=item;
		last.next=null;
		if(isEmpty()) first=last;
		else oldlast.next=last;
		N++;
	}
	
	// 从表头删除元素
	public Item dequeue(){
		Item item=first.item;
		first=first.next;
		if(isEmpty()) last=null;
		N--;
		return item;
	}
	
	public Iterator<Item> iterator(){
		return new ListIterator();
	}
	private class ListIterator implements Iterator<Item>{
		Node current=first;
		@Override
		public boolean hasNext() {
			return current!=null;
		}

		@Override
		public Item next() {
			Item item=current.item;
			current=current.next;
			return item;
		}

		@Override
		public void remove() {}
		
	}
	public static void main(String[] args) {
		MyQueue<String> q=new MyQueue<String>();
		Scanner cin=new Scanner(System.in);
		while(cin.hasNext()){
			String item=cin.next();
			if(item.equals("$")) break;
			if(!item.equals("-")){
				q.enqueue(item);
				System.out.print("enqueue "+item);
			}
			else if(!q.isEmpty()){
				System.out.print("dequeue "+q.dequeue());
			}
			System.out.println(" | "+q.size()+" left in queue");
		}
		// Test iterator
		for(String s : q){
			System.out.print(s+" ");
		}
		System.out.println();
		
		Iterator<String> it=q.iterator();
		while(it.hasNext()){
			System.out.print(it.next()+" ");
		}
	}
}
// Test example
to be or not to - be - - that - - - is $
enqueue to | 1 left in queue
enqueue be | 2 left in queue
enqueue or | 3 left in queue
enqueue not | 4 left in queue
enqueue to | 5 left in queue
dequeue to | 4 left in queue
enqueue be | 5 left in queue
dequeue be | 4 left in queue
dequeue or | 3 left in queue
enqueue that | 4 left in queue
dequeue not | 3 left in queue
dequeue to | 2 left in queue
dequeue be | 1 left in queue
enqueue is | 2 left in queue
that is 
that is 


没有更多推荐了,返回首页