两个栈构造队列:很简单只实现了最基本的功能。
import java.util.*;
class Queue<T>
{
private Stack<T> s1;
private Stack<T> s2;
private int size=0;
public Queue()
{
s1 = new Stack<T>();
s2 = new Stack<T>();
}
public void offer(T x)
{
s1.add(x);
size++;
}
public T poll()
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
size--;
return s2.pop();
}
public T peek()
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
return s2.peek();
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size==0?true:false;
}
public String toString()
{
peek();
return s2.toString();
}
}
public class scanner{
public static void main(String args[]) {
Queue<String> q = new Queue<String>();
String str ;
q.offer("1");
q.offer("2");
q.offer("3");
System.out.println(q.toString());
q.poll();
System.out.println(q.toString());
q.offer("4");
System.out.println(q.toString());
}}
结果如下:
[3, 2, 1]
[3, 2]
[3, 2, 4]