简体   繁体   中英

Java: How to create a stack using the queue interface?

I have a function that takes Queues, and I would like to perform operations on them like a Stack. Unfortunately, ArrayDeque methods like addFirst are not visible in the Queue interface, so I cannot use them. Is there a way to perform Stack operations on a Queue?

Thanks!

There is! Check out asLifoQueue(Deque<T> deque) in the Collections class. https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#asLifoQueue(java.util.Deque)

Returns a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.

It returns a new class that implements the Queue interface, except rebinding the Queue methods to the corresponding methods in Your Deque, so that it functions as a LIFO stack!

The Java library is full of magical things if you look for them!

NOTE: If you can't use a OO approach like below, just the a queue like q , and manipulate the queue as presented below.

If you have to use a Queue, this is a decent solution, although a much better approach would be to us the Stack class, or implement a Stack using other data structures.

public class MyStack<T> {

/**
 * @param args
 */
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
    MyStack<String> s = new MyStack<String>();
    s.push("1");
    s.push("2");
    s.push("3");
    s.push("4");
    System.out.println(s.pop());
    System.out.println(s.pop());
    System.out.println(s.pop());
    System.out.println(s.pop());
    System.out.println(s.pop());
}

public void push(T s){
    q.offer(s);         
}

public T pop(){
    int n = q.size();
    for(int i = 0; i < n-1; i++){
        q.offer(q.poll());              
    }
    return q.poll();
}
}

Output:
4
3
2
1
null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM