剑指offer-用两个队列实现栈

剑指offer-用两个队列实现栈

  • 题目描述
  • 解题思路
  • 代码块

题目描述

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

解题思路

运用两个stack实现队列,首先把两个队列尾部相对。队列的Push操作,首先要判断stack2是否为空,如不为空则先将stack2内的元素pop,然后push到stack1当中;队列的Pop操作,首先判断stack1是否为空,如stack1为空,选择返回-1,如果不为空将stack1值push到stack2中,然后pop出stack2中的第一个值。

代码块

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;
    
    }
}

你可能感兴趣的:(剑指offer)