力扣解题:如何用栈实现队列,用队列实现栈?

101 阅读1分钟

1)队列的基本实现

/**
 * 队列实现
 */
Queue<Integer>queue=new LinkedList<>();
//添加元素
queue.offer(1);
queue.offer(2);
queue.offer(3);
//第二种方式添加
/*queue.add(1);
queue.add(2);
queue.add(3);*/
//取出元素
Integer poll1 = queue.poll();
System.out.println(poll1);
//查找元素
Integer peek = queue.peek();
System.out.println("查找并不实际弹出队列:"+peek);

2)栈的基本实现

/**
 * 栈实现1
 */
Deque<Integer>stack=new LinkedList<>();
stack.push(1);
stack.push(2);
stack.push(3);
Integer pop = stack.pop();
System.out.println("弹出栈:"+pop);
Integer peek2 = stack.peek();
System.out.println("不实际弹出栈,查询:"+peek2);


/**
 * 栈实现2
 */
Stack<Integer> stack1=new Stack<>();
stack1.push(1);
stack1.push(2);
stack1.push(3);
Integer pop1 = stack1.pop();
System.out.println("弹出栈:"+pop1);
Integer peek3 = stack1.peek();
System.out.println("不实际弹出栈,查询:"+peek3);

3)解题:队列实现栈(对应力扣225题)

 

public class MyStack {
    Queue<Integer>queue1=null;
    Queue<Integer>queue2=null;
    public MyStack() {
        queue1=new LinkedList<Integer>();
        queue2=new LinkedList<Integer>();
    }
    public void push(int x) {
        queue2.add(x);
        while (!queue1.isEmpty()){
            queue2.add(queue1.poll());
        }
        Queue<Integer> tempQueue=queue1;
        queue1=queue2;
        queue2=tempQueue;
    }
    public int pop() {
        return queue1.poll();
    }
    public int top() {
        return queue1.peek();
    }
    public boolean empty() {
        return queue1.isEmpty();
    }
}

4)解题:栈实现队列(对应力扣232题)

//栈实现队列
public class MyQueue {
    Stack<Integer>stack1=null;
    Stack<Integer>stack2=null;
    public MyQueue() {
        stack1=new Stack<>();
        stack2=new Stack<>();
    }
    public void push(int x) {
        stack1.push(x);
    }
    public int pop() {
        if (stack2.isEmpty()){
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
    public int peek() {
        int result =pop();
        stack2.push(result);
        return result;
    }
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

 

高性能云服务器

精品线路独享带宽,毫秒延迟,年中盛惠 1 折起