两个栈实现队列和两个队列实现栈

实现队列

import java.util.Stack;

/**
 * @Description:
 */
public class List {
    private int size;
    private Stack<Integer> stack1 = new Stack<>();
    private Stack<Integer> stack2 = new Stack<>();

    public List(int size) {
        this.size = size;
    }

    public void add(Integer a) {
        stack1.push(a);
    }

    public Object get() {
        if(stack2.empty()) {
            while(!stack1.empty()) {
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        } else {
            return stack2.pop();
        }
    }
}

 

实现栈

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description:
 */
public class Stack {
    LinkedList<Integer> queue1 = new LinkedList<>();
    LinkedList<Integer> queue2 = new LinkedList<>();

    public Stack() {

    }

    public int pop() {
        int temp;
        if(queue1.size() == 0 && queue2.size() == 0) {
            return -1;
        } else if(queue1.size() != 0) {
            while(queue1.peek() != null) {
                temp = queue1.pop();
                if(queue1.peek() == null) {
                    return temp;
                }
                queue2.offer(temp);
            }
        } else {
            while(queue2.peek() != null) {
                temp = queue2.pop();
                if(queue2.peek() == null) {
                    return temp;
                }
                queue1.offer(temp);
            }
        }
        return -1;
    }

    public void push(int a) {
        if(queue1.size() == 0 && queue2.size() == 0) {
            queue1.offer(a);
        } else if(queue1.size() != 0) {
            queue1.offer(a);
        } else {
            queue2.offer(a);
        }
    }
}

 

展开阅读全文

没有更多推荐了,返回首页