java 数据结构队列

队列是基于先进先出的模式(First  In First Out, 简称FIFO)。队列的操作有:

在java中:

offer()/add()均可执行入栈的操作,它们的区别是,当超出队列界限的时候,add()会直接抛出异常等你处理,而offer()有事先判断的所以放回false

pop()/remove()方法都是从队列中删除第一个元素,区别是,队列为空时,调用remove()会抛出异常而pop()则会返回null。

element() 和 peek()方法用来查询头部元素即第一个元素,类似,peek()在队列为空时返回null,而element()会抛出异常。

如图:在队尾处不断添加元素,在队头出对。



//下面是队列的基本实现
class Queue {
	private int maxSize;
	private long[] queArray;
	private int front;
	private int rear;
	private int nItems;

	public Queue(int s) {
		maxSize = s;
		queArray = new long[maxSize];
		front = 0;
		rear = -1;
		nItems = 0;
	}

	public void insert(long j) {
		if (rear == maxSize - 1)
			rear = -1;
		queArray[++rear] = j;
		nItems++;
	}

	public long remove() {
		long temp = queArray[front++];
		if (front == maxSize)
			front = 0;
		nItems--;
		return temp;
	}

	public boolean isEmpty() {
		return (nItems == 0);
	}

	public boolean isFull() {
		return (nItems == maxSize);
	}

	public int size() {
		return nItems;
	}

	public void display() {
		// TODO Auto-generated method stub
		
		if (rear >= front) {
			for (int i = front; i <= rear; i++) {
				System.out.print(queArray[i] + " ");
			}
		}
		else {
			for (int i = front; i < maxSize; i++) {
				System.out.print(queArray[i] + " ");
			}
			for (int i = 0; i <= rear; i++) {
				System.out.print(queArray[i] + " ");
			}
		}
		System.out.println();

	}
}
class QueueApp {
	public static void main(String[] args) {
		Queue theQueue = new Queue(5); 
		
		theQueue.insert(10); 
	        theQueue.insert(20);
		theQueue.insert(30);
	        theQueue.insert(40);
	        theQueue.insert(50);
	    
	        theQueue.display();
	  
	
		theQueue.remove(); 
		theQueue.remove(); 
		theQueue.remove();
		
		theQueue.insert(50); 
		theQueue.insert(60);
		theQueue.insert(70);
		
		
		theQueue.display();
			
	}		
} 

//结果

10 20 30 40 50 
40 50 50 60 70 


猜你喜欢

转载自blog.csdn.net/legendaryhaha/article/details/79812957