用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 

方法一:运行时间:10ms

import java.util.Stack;
 
public class Solution {
    Stack stack1 = new Stack();
    Stack stack2 = new Stack();
     
    public void push(int node) {
        stack1.push(node);
    }
     
    public int pop() {
        if(stack1.empty()&&stack2.empty()){
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

 

方法二:执行用时:68 ms,

class CQueue {
    Stack stack1 = new Stack();
    Stack stack2 = new Stack();
    int size = 0;;
    
    public void appendTail(int value){
        stack1.push(value);
        size++;
    }
    
    public int deleteHead(){
        if(size == 0) return -1;
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        size--;
        return stack2.pop();
    }
}

 

你可能感兴趣的:(算法,队列,栈,算法)