使用Java中的链接列表实现队列

时间:2020-02-23 14:34:24  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中使用链接列表来实现队列。
队列是抽象数据类型,首先演示(FIFO)行为。
我们将使用数组实施相同的行为。
虽然Java提供了所有抽象数据类型的实现,如堆栈,队列和链接列表,但它始终是理解基本数据结构并自己实现它们的好主意。
请注意,LinkedList队列的实现是动态的。
队列中有两个最重要的操作:enqueue:当我们将元素插入队列时的操作。
Dequeue:当我们从队列中删除元素时的操作。

使用链接列表实现队列的Java程序:

package org.igi.theitroad;
public class QueueUsingLinkedListMain
{
 private Node front, rear; 
 private int currentSize; //number of items
 
 //class to define linked node
 private class Node
 { 
 int data;
 Node next;
 }
 
 //Zero argument constructor
 public QueueUsingLinkedListMain()
 {
 front = null;
 rear = null;
 currentSize = 0;
 }
 
 public boolean isEmpty()
 {
 return (currentSize == 0);
 }
 
 //Remove item from the beginning of the list.
 public int dequeue()
 {
 int data = front.data;
 front = front.next;
 if (isEmpty()) 
 {
 rear = null;
 }
 currentSize--;
 System.out.println(data+ " removed from the queue");
 return data;
 }
 
 //Add data to the end of the list.
 public void enqueue(int data)
 {
 Node oldRear = rear;
 rear = new Node();
 rear.data = data;
 rear.next = null;
 if (isEmpty()) 
 {
 front = rear;
 }
 else 
 {
 oldRear.next = rear;
 }
 currentSize++;
 System.out.println(data+ " added to the queue");
 }
 public static void main(String a[]){
 
 QueueUsingLinkedListMain queue = new QueueUsingLinkedListMain();
 queue.enqueue(6);
 queue.dequeue();
 queue.enqueue(3);
 queue.enqueue(99);
 queue.enqueue(56);
 queue.dequeue();
 queue.enqueue(43);
 queue.dequeue();
 queue.enqueue(89);
 queue.enqueue(77);
 queue.dequeue();
 queue.enqueue(32);
 queue.enqueue(232);
 }
}

运行上面的程序时,我们将得到以下输出:

6 added to the queue
6 removed from the queue
3 added to the queue
99 added to the queue
56 added to the queue
3 removed from the queue
43 added to the queue
99 removed from the queue
89 added to the queue
77 added to the queue
56 removed from the queue
32 added to the queue
232 added to the queue