4.队列
在计算机科学中,队列是一种数据结构,有点类似栈,只是在队列中第一个插入的数据项也会是最先被移除(First In First Out,先进先出),而在栈中,最后插入的数据项最先移除(Last In First Out,后进先出)。队列的作用就像电影院前的人们站成的排一样:第一个进入队尾的人将最先到达队头买票。最后排队的人最后才能买到票。
在计算机(或者网络)操作系统里,有各种队列在安静的工作着。打印作业在打印队列中等待打印。当在键盘上敲击时,也有一个存储键入内容的队列。同样,如果使用文字处理程序敲击一个键,而计算机又暂时要做其他的事,敲击的内容不会丢失,在会排在队列中等待,直到文字处理程序有时间来读取它。利用队列保证了键入内容在处理时其顺序不会改变。
循环队列java代码实现:
- package Queue;
- //queue.java
- //demonstrate queue
- public class queue {
- private int maxSize;
- private long[]queArray;
- private int front;
- private int rear;
- private int nItems;
- //..............................................................
- public queue(int s)//constructor
- {
- maxSize=s;
- queArray=new long[maxSize];
- front=0;
- rear=-1;
- nItems=0;
- }
- //..............................................................
- public void insert(long j)
- { if(nItems!=maxSize)
- { if(rear==maxSize-1) //deal with wraparound
- rear=-1;
- queArray[++rear]=j; //increment rear and insert
- nItems++;//one more item
- }
- else System.out.println("The queue is full,please wait");
- }
- //..............................................................
- public long remove() //take item from front of queue
- {
- if(nItems!=0)
- {
- long temp=queArray[front++]; //get value and increase front
- if(front==maxSize) //deal with wraparound
- front=0;
- nItems--; //one less item
- return temp;
- }
- else System.out.println("No item left yet");
- return 0;
- }
- //..............................................................
- public long peekFront()
- {
- return queArray[front];
- }
- //..............................................................
- public int size()
- {
- return nItems;
- }
- //..............................................................
- public boolean isEmpty()
- {
- return (nItems==0);
- }
- }
- package Queue;
- public class QueueApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- queue theQueue=new queue(5);
- theQueue.insert(10);
- theQueue.insert(20);
- theQueue.insert(30);
- theQueue.insert(40);
- theQueue.remove();
- theQueue.remove();
- theQueue.remove();
- theQueue.insert(50);
- theQueue.insert(60);
- theQueue.insert(70);
- theQueue.insert(80);
- while(!theQueue.isEmpty())
- {
- long n=theQueue.remove();
- System.out.print(n);
- System.out.print(" ");
- }
- System.out.print(" ");
- }//end main()
- } // end class QueueApp
结果:
- 40 50 60 70 80