Wins the stacks two queues implemented offer-

Wins the stacks two queues implemented offer-

Title Description

Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.

Problem-solving ideas

The use of two stack queue, the first two opposite end of the queue. Push queue operation, must first determine whether stack2 is empty, if not empty then the first element in a pop stack2, then to push them stack1; Pop operation queue, first determines whether stack1 is empty, as stack1 is empty, select return -1 if not empty to push the value stack1 stack2 then pop the first value of stack2.

Block

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        int val=0;
    	while(!stack2.empty()){
    		val=stack2.pop();
    		stack1.push(val);
    	}
        stack1.push(node);
    }
    
    public int pop() {
        int val=0;
    	while(!stack1.empty()){
    		val=stack1.pop();
    		stack2.push(val);
    	}
    	if(!stack2.empty()){
    	    val=stack2.pop();
    	    return val;
    	}
    	else 
    		return -1;
    
    }
}
Released seven original articles · won praise 1 · views 159

Guess you like

Origin blog.csdn.net/liqiao96/article/details/105148592
Recommended