利用两个栈实现队列的入队出队

利用两个栈实现队列的入队出队_第1张图片

import java.util.ArrayList;
import java.util.Stack;

/** @author:micro_hz 2015年8月18日 */
public class Quen {
    //初始化两个栈
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    //第二个栈计数,入第二个栈时候需要用
    int num = 0;
    public void push(int node) {
        stack1.add(node);
        num ++;
        //若第二只有一个
        if(num == 1)
        {
            stack2.add(stack1.pop());
        }
        if(num > 1)
        {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < num - 1; i++) {
                list.add(stack2.pop());
            }
            stack2.add(stack1.pop());
            for (int i = list.size() - 1; i >= 0; i --) {
                stack2.push(list.get(i));
            }
        }
    }

    public int pop() {
        num --;
        return stack2.pop();
    }
}

方法2:

import java.util.ArrayList;
import java.util.Stack;

/** @author:micro_hz 2015年8月18日 */
public class Quen {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    int num = 0;
    public void push(int node) {
        stack1.add(node);

        if(num == 0)
        {
            stack2.add(stack1.pop());
            num ++;
        }
        else 
        {
            ArrayList<Integer> list = new ArrayList<Integer>();
            while(!stack2.isEmpty())
            {
                list.add(stack2.pop());
            }
            stack2.add(stack1.pop());
            num ++;
            for (int i = list.size() - 1; i >= 0; i --) {
                stack2.push(list.get(i));
            }
        }
    }

    public int pop() {
        num --;
        return stack2.pop();
    }
}

不利用集合:

import java.util.Stack;
public class Solution {

   Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
   public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if(!stack2.isEmpty())
        {
            return stack2.pop();
        }
        while(!stack1.isEmpty())
        {
            stack2.push(stack1.pop());
        }

        return stack2.pop();
    }
}

你可能感兴趣的:(栈)