[Java] 232. Use the stack to implement the queue --- quickly learn the usage of the Stack class (stack)! ! !

Please use only two stacks to implement a first-in first-out queue. The queue should support all operations supported by the general queue (push, pop, peek, empty):

Implement the MyQueue class:

void push(int x) Push element x to the end of the queue
int pop() Remove from the beginning of the queue and return the element
int peek() Return the element at the beginning of the queue
boolean empty() If the queue is empty, return true; otherwise, Return false

Description:

You can only use standard stack operations-that is, only push to top, peek/pop from top, size, and is empty operations are legal.
The language you are using may not support stacks. You can use list or deque (double-ended queue) to simulate a stack, as long as it is a standard stack operation.

Advanced:

Can you implement a queue with O(1) amortized time for each operation? In other words, the total time complexity of performing n operations is O(n), even if one of the operations may take a long time.

Example:

Input:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
Output:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

prompt:

1 <= x <= 9
Call push, pop, peek and empty up to 100 times,
assuming that all operations are valid (for example, an empty queue will not call pop or peek operations)

代码:
private Stack<Integer> queue1;
	private Stack<Integer> queue2;
    public MyQueue() {
    
    
         queue1=new Stack<>();
         queue2=new Stack<>();
    }
    public void push(int x) {
    
    
          queue1.push(x);
    }
    
    public int pop() {
    
    
    	stackTranqueue();
    	int x=queue2.pop();
    	while(!queue2.empty()) {
    
    
   		 queue1.push( queue2.pop());
   	    }
		return x;

    }
    public int peek() {
    
    
    	stackTranqueue();
    	int x=queue2.pop();
    	queue1.push(x);
    	while(!queue2.empty()) {
    
    
   		 queue1.push( queue2.pop());
   	    }
		return x;

    }
    public boolean empty() {
    
    
		return queue1.empty();

    }
    //栈queue1转化成queue2
    public void stackTranqueue() {
    
     
    	 while(!queue1.empty()) {
    
    
    		 queue2.push( queue1.pop());
    	 }
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114383187