数据结构与算法12-栈和队列-循环队列-优先级队列

无数据项计数的循环队列算法:java

在判满和判空须要注意,因为是循环队列,因此有可能rear和front指针指向同一位置,可是出现的状况有不少,形成可空可满的状况,因此数据项要比存储空间少一,这样就能解决此问题。算法

又由于没有数据项技术,因此在统计数据项个数时也应该注意,若是front>rear用maxsize-front+(rear+1),不然用rear-front+1便可。指针

class Queue2 {
	private int maxSize;
	private long[] queArray;
	private int front;
	private int rear;
	public Queue2(int s)
	{
		maxSize = s+1;
		queArray = new long[maxSize];
		front = 0;
		rear = -1;
		
	}
	public void insert(long j)
	{
		if(rear == maxSize - 1);
		rear = -1;
		queArray[++rear] = j;
		
	}
	public long remove()
	{
		long temp = queArray[front++];
		if(front == maxSize)
			front = 0;
	
		return temp;
	}
	public long peekFront()
	{
		return queArray[front];
	}
	public boolean isEmpty()
	{
		return (rear+1==front||front+maxSize-1==rear);
	}
	public boolean isFull()
	{
		return (rear+2==front||front+maxSize-2==rear);
	}
	public int size()
	{
		if(rear >= front)
			return rear-front+1;
		else
			return (maxSize-front)+(rear+1);
				}
}
class QueueApp2
{
	public static void main(String[] args)
	{
		Queue2 theQueue = new Queue2(5);
		theQueue.insert(10);
		theQueue.insert(11);
		theQueue.insert(12);
		theQueue.insert(14);
		theQueue.remove();
		theQueue.remove();
		theQueue.remove();
		theQueue.insert(77);
		theQueue.insert(88);
		theQueue.insert(99);
		theQueue.insert(77777);
		while(!theQueue.isEmpty())
		{
			long n = theQueue.remove();
			System.out.println(n);
			System.out.println(" ");
		}
		System.out.println(" ");
	}
}

队列效率:插入,移除速度均为O(1)。code

双端队列:队列

双端队列就是一个两端都是结尾的队列。队列的每一端均可以插入数据项和溢出数据项。这些方法能够叫作insertLeft()和insertRight(),以及removLeft()和removeRight().rem

若是严格禁止调用insertLeft()和removeLeft方法,那么双端队列就是栈。禁用insertLeft()和removeRight(或相反的另外一对方法),它的功能就和队列同样了。双端队列在容器类库中有时会提供栈和队列的功能。it

优先级队列io

根据关键字大小决定数据项在队列中的位置class

import java.io.IOException;


class priorityQ {
	private int maxSize;
	private long[] queArray;
	private int nItems;
	public priorityQ(int s)
	{
		maxSize = s;
		queArray = new long[maxSize];
		nItems = 0;
	}
	public void insert(long item)
	{
		int j;
		if(nItems==0)
			queArray[nItems++] = item;
		else
		{
			for(j=nItems-1;j>=0;j--)
			{
				if(item > queArray[j])
					queArray[j+1] = queArray[j];
				else
					break;
			}
			queArray[j+1] = item;
			nItems++;
		}
	}
		public long remove()
		{
			return queArray[--nItems];
		}
		public long peekMin()
		{
			return queArray[nItems - 1];
		}
		public boolean isEmpty()
		{
			return (nItems==0);
		}
		public boolean isFull()
		{
			return (nItems==maxSize);
		}
		}
	class priorityQApp
	{
		public static void main(String[] args) throws IOException
		{
			priorityQ thePQ = new priorityQ(5);
			thePQ.insert(30);
			thePQ.insert(50);
			thePQ.insert(10);
			thePQ.insert(20);
			thePQ.insert(40);
			while(!thePQ.isEmpty())
			{
				long item = thePQ.remove();
				System.out.println(item + " ");
				
			}
			System.out.println(" ");
		}
	}
10 
20 
30 
40 
50

优先级效率:效率

插入,删除都为O(N)

可是数据项数量大,通常会采用堆

相关文章
相关标签/搜索