2018年10月31日
隊(duì)列是一種先進(jìn)先出(FIFO)
的數(shù)據(jù)結(jié)構(gòu)
1够滑,隊(duì)列的鏈表實(shí)現(xiàn)
public class ListQueue<Item> implements Iterable<Item> {
private class Node {
Item item;
Node next;
}
private Node first;
private Node last;
private int N;
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void enqueue(Item item) {
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) {
first = last;
} else {
oldLast.next = last;
}
N++;
}
public Item dequeue() {
Item item = first.item;
first = first.next;
if (isEmpty()) {
last = null;
}
N--;
return item;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator(first);
}
private class ListIterator implements Iterator<Item> {
private Node current;
public ListIterator(Node first) {
current = first;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = current.item;
current = current.next;
return item;
}
}
}
2添怔,隊(duì)列的數(shù)組實(shí)現(xiàn)
public class ResizingArrayQueue<Item> implements Iterable<Item> {
private Item[] a = (Item[]) new Object[2];
private int N;
private int first;
private int last;
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int max) {
Item[] temp = (Item[]) new Object[max];
for (int i = 0; i < N; i++) {
temp[i] = a[(first + i) % a.length];
}
a = temp;
first = 0;
last = N;
}
public void enqueue(Item item) {
if (N == a.length) {
resize(2 * a.length);
}
a[last++] = item;
if (last == a.length) {
//環(huán)形數(shù)組,到底了從頭計(jì)數(shù)
last = 0;
}
N++;
}
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item item = a[first];
//避免對(duì)象游離续徽,即保存一個(gè)不需要的對(duì)象的引用
a[first] = null;
first++;
N--;
if (first == a.length) {
//環(huán)形數(shù)組畏妖,到底了從頭開始
first = 0;
}
if (N > 0 && N == a.length / 4) {
resize(a.length / 2);
}
return item;
}
@Override
public Iterator<Item> iterator() {
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
@Override
public boolean hasNext() {
return i < N;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = a[(first + i) % a.length];
i++;
return item;
}
}
}
3,隊(duì)列的應(yīng)用
- 圓圈中最后剩下的數(shù)字
題目:0, 1, …, n-1這n個(gè)數(shù)字排成一個(gè)圓圈踢代,從數(shù)字0開始每次從這個(gè)圓圈里刪除第m個(gè)數(shù)字盲憎。求出這個(gè)圓圈里剩下的最后一個(gè)數(shù)字。
public int lastRemainingSolution(int n, int m) {
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
queue.offer(i);
}
int count = 0;
int result = -1;
while (!queue.isEmpty()) {
if (count == m - 1) {
result = queue.poll();
count = 0;
}
if (!queue.isEmpty()) {
queue.offer(queue.poll());
}
count++;
}
return result;
}