先挖个坑,回头再补上
1 用队列创建栈
import java.util.Stack;
public class QueueBuilderByStack {
public static void main(String[] args) {
QueueBuilderByStack queueBuilderByStack = new QueueBuilderByStack();
queueBuilderByStack.offer("A");
queueBuilderByStack.offer("B");
queueBuilderByStack.offer("C");
System.out.println(queueBuilderByStack.toString());
for (int i = 0; i < 2; i++) {
System.out.println(queueBuilderByStack.poll());
}
queueBuilderByStack.offer("D");
queueBuilderByStack.offer("E");
System.out.println(queueBuilderByStack.poll());
System.out.println(queueBuilderByStack.poll());
}
private static Stack in = new Stack();
private static Stack out = new Stack();
public Object[] toArray() {
Object[] array = new Object[in.size() + out.size()];
System.arraycopy(in.toArray(), 0, array, 0, in.size());
System.arraycopy(out.toArray(), 0, array, in.size() - 1, out.size());
return array;
}
public boolean add(Object o) {
in.add(o);
return true;
}
public Object poll() {
if (out.isEmpty()) {
if (in.isEmpty()) {
return null;
} else {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
return out.pop();
}
public Object peek() {
if (out.isEmpty()) {
if (in.isEmpty()) {
return null;
} else {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
return out.peek();
}
public boolean offer(Object o) {
in.push(o);
return true;
}
public boolean remove(Object o) {
if (in.contains(o)) {
in.remove(o);
} else if (out.contains(o)) {
out.remove(o);
}
return true;
}
}
2.用栈创建队列
import java.util.PriorityQueue;
import java.util.Queue;
public class StackBuilderByQueue<E> {
private static Queue q1 = new PriorityQueue();
private static Queue q2 = new PriorityQueue();
public static void main(String[] args) {
StackBuilderByQueue stackBuilderByQueue = new StackBuilderByQueue();
stackBuilderByQueue.push("A");
stackBuilderByQueue.push("B");
stackBuilderByQueue.push("C");
System.out.println(stackBuilderByQueue.toString());
System.out.println(stackBuilderByQueue.poll());
System.out.println(stackBuilderByQueue.toString());
stackBuilderByQueue.push("D");
System.out.println(stackBuilderByQueue.toString());
System.out.println(stackBuilderByQueue.poll());
System.out.println(stackBuilderByQueue.toString());
}
@Override
public String toString() {
return "in:" + String.join(",", q1) +
" out:" + String.join(",", q2);
}
public E push(E item) {
if (q1.isEmpty() && q2.isEmpty()) {
q1.offer(item);
} else if (q1.isEmpty()) {
q2.offer(item);
} else if (q2.isEmpty()) {
q1.offer(item);
}
return item;
}
public E poll() {
if (q1.isEmpty() && q2.isEmpty()) {
return null;
} else if (q1.isEmpty()) {
while (q2.size() != 1) {
q1.offer(q2.poll());
}
return (E) q2.poll();
} else if (q2.isEmpty()) {
while (q1.size() != 1) {
q2.offer(q1.poll());
}
return (E) q1.poll();
}
return null;
}
}
网友评论