Java隊(duì)列是一種基于先進(jìn)先出(FIFO)原則的數(shù)據(jù)結(jié)構(gòu),其中新的元素在隊(duì)列的尾部添加,而舊的元素則從隊(duì)列的頭部移除。隊(duì)列由兩個(gè)指針來(lái)操作:頭指針和尾指針。
public class Queue { private Node head; private Node tail; public Queue() { head = null; tail = null; } public void enqueue(Object data) { Node newNode = new Node(data); if (tail == null) { head = newNode; tail = newNode; } else { tail.next = newNode; tail = newNode; } } public Object dequeue() { if (head == null) { return null; } else { Object data = head.data; head = head.next; if (head == null) { tail = null; } return data; } } private class Node { Object data; Node next; Node(Object data) { this.data = data; this.next = null; } } }
上面的代碼定義了一個(gè)名叫Queue的類,其中頭指針(head)指向隊(duì)列的頭部,尾指針(tail)指向隊(duì)列的尾部。enqueue方法用于向隊(duì)列中添加元素,它將新元素添加到尾指針?biāo)傅奈恢蒙稀equeue方法用于從隊(duì)列中移除元素,它將頭指針?biāo)傅脑匾瞥㈩^指針指向下一個(gè)元素。