# 面试题精选:循环队列

public interface BoundedQueue {
int peek();
int poll();
boolean isEmpty();
boolean isFull();
}


public class MyBoundedQueue implements BoundedQueue {
private int tail = 0;
private int[] arr;

public MyBoundedQueue(int cap) {
this.arr = new int[cap];
}
@Override
if (isFull()) {
return false;
}
arr[tail++] = e;
return true;
}

@Override
public int peek() {
if (isEmpty()) {
return -1;
}
return arr[0];
}

@Override
public int poll() {
if (isEmpty()) {
return -1;
}
int res = arr[0];
for (int i = 0; i < tail-1; i++) {
arr[i] = arr[i+1];
}
tail--;
return res;
}

@Override
public boolean isEmpty() {
return tail == 0;
}

@Override
public boolean isFull() {
return tail == arr.length;
}
}


public class CircularBoundedQueue implements BoundedQueue {
private int tail = 1;
private int[] arr;

public CircularBoundedQueue(int cap) {
this.arr = new int[cap+1];
}
@Override
if (isFull()) {
return false;
}
arr[tail] = e;
tail = next(tail);
return true;
}

@Override
public int peek() {
if (isEmpty()) {
return -1;
}
}

@Override
public int poll() {
if (isEmpty()) {
return -1;
}
}

@Override
public boolean isEmpty() {
}

@Override
public boolean isFull() {
}

private int next(int cur) {
return (cur+1)%arr.length;
}
}


public class CircularBoundedQueue2 implements BoundedQueue {
private class Node {
int value;
Node next;
}

private Node tail;

public CircularBoundedQueue2(int cap) {
Node p = new Node();
for (int i = 0; i < cap; i++) {
Node newNode = new Node();
p.next = newNode;
p = p.next;
}
}
@Override
if (isFull()) {
return false;
}
tail.value = e;
tail = tail.next;
return true;
}

@Override
public int peek() {
if (isEmpty()) {
return -1;
}
}

@Override
public int poll() {
if (isEmpty()) {
return -1;
}
}

@Override
public boolean isEmpty() {
}

@Override
public boolean isFull() {
}
}

xindoo CSDN认证博客专家 Linux 分布式 Spring

09-08 1万+
12-15 2206

04-11 2609
11-04 613
07-30 823
07-14 206
06-14 43