Two stacks implement queues

Topic description:

Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Ideas:

stack: first in, last out

Queue: first in first out

Push elements directly into stack1

To delete an element, first check whether stack2 is empty, and pop it up if it is not empty; if it is empty, take out the element in stack1 and place it in stack2

Code:

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 利用两个栈来实现队列功能
 * @time: 2018年04月26日
 * @modifytime:
 */
public class StackQueue
{
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    public void push(Integer i){
        stack1.push(i);
    }
    public Integer pop(){
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){ // 重点:每次stack2取完之后,将所有stack1中所有的元素放到stack2中
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        StackQueue sq = new StackQueue();
        sq.push(1);
        sq.push(2);
        sq.push(3);
        sq.push(4);
        System.out.println(sq.pop() + ":" + sq.pop() + ":" + sq.pop() + ":" + sq.pop());
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324988341&siteId=291194637