数据结构——使用双端链表实现队列(java实现)

来源:互联网 发布:吉林大学校网络教育 编辑:程序博客网 时间:2024/06/05 21:18

     队列是这样一种数据结构:在队尾(rear)插入数据项,在队首(front)移除数据项,队列的进出顺序是先进入的先被移除(先进先出,FIFO);

     Robert Lafore的书对队列的使用有如下描述:“它可以用于模拟真实世界的环境,例如模拟人们在银行里排队等待,飞机等待起飞,或者因特网上数据包等待传送。在计算机(或网络)操作系统里,有各种队列在安静地工作着。打印作业在打印队列中等待打印。当在键盘上敲击时,也有一个存储键入内容的队列。同样,如果使用文字处理程序敲击一个键,而计算机又暂时要做其他的事,敲击的内容不会丢失,它会排在队列中等待,知道文字处理程序有时间来读取它。利用队列保证了键入内容在处理时其顺序不会改变。

实现代码如下:

/* *Imagine a queue in front of you,your left side is the front of the queue,your right side is the rear of queue; *this seems more logical and close to real life **/class Link{public long dData;public Link next;public Link(long dData){this.dData = dData;}public void displayLink(){System.out.print("{" + this.dData + "}");}}class FirstLastList{Link first;Link last;public FirstLastList(){this.first = null;  //when create an object of LinkList,make sure it is empty!this.last = null;}public boolean isEmpty(){return first == null;}public void insertLast(long key)//this method will be used when I create insert() method {//in Queue(not the class Queue,I just mean a Queue)Link newLink = new Link(key);if(this.isEmpty())//if list is empty{first = newLink;//draw a picture can help me understand it !last = newLink;newLink.next = null;}else{last.next = newLink;last = newLink;newLink.next = null;}}public long deleteFirst()//this method will be used when I create remove() method in Queue(not the class Queue,I just mean a Queue){Link current = null;if(this.isEmpty()){System.out.println("Your stack is empty");return -1;}else if(first==last){current = first;    first = null;    last = null;    return current.dData;}else{current = first;first = first.next;return current.dData;}}public void displayList(){Link current = first;System.out.print("Queue (front-->rear): ");if(this.isEmpty()){System.out.println("Your list is empty, nothing to show!");}else{while(current!=null){current.displayLink();current = current.next;}System.out.println("");}}}class LinkQueue{FirstLastList list = new FirstLastList();//two-ended listpublic void insert(long key){list.insertLast(key);}public long remove(){return list.deleteFirst();}public void showQueue(){list.displayList();}}class LinkQueueApp{public static void main(String[] args){LinkQueue theQueue = new LinkQueue();theQueue.insert(12);//insert four elementstheQueue.insert(13);theQueue.insert(14);theQueue.insert(15);theQueue.showQueue();//look at what is in the queuetheQueue.remove();//remove two elements ,from right sidetheQueue.remove();theQueue.showQueue();//look at what is in the queue now!}}

代码的思路:首先创建一个新队列,接着在队列中一次插入12、13、14、15,在队列头部进行两次移除操作,最后运行结果如下:


0 0
原创粉丝点击