剑指offer面试题9:用两个栈实现队列(Java 实现)

本文介绍了一种使用两个栈实现队列的方法,通过巧妙地切换数据存储和弹出操作,实现了队列的基本功能。同时,也探讨了如何利用两个队列来实现栈的数据结构,为数据结构的灵活运用提供了新的视角。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:用两个栈实现一个队列,队列的声明如下,请实现它的两个类appendTail(Integer data)和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。

话不多说,直接撸上代码:

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.size()<=0){
            while(stack1.size()>0){
            Integer data  = stack1.pop();
            stack2.push(data);    
            }
          }
        if(stack2.size()<=0){
            return (Integer)null;
        }
        return stack2.pop();
    }
}

思路;有两个栈stack1和是stack2。当有数据插入时,我们统一将他们放在stack1中,取数据的时候,我们将stack1中的数据全部弹出,弹入到stack2中。当我们取数据的时候,如果stack2.size()>0,直接stack2.pop()即可;依次循环。

用两个队列实现栈

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class TwoQueueImplStack {
	Queue<Integer> queue1 = new ArrayBlockingQueue<Integer>(100);
    Queue<Integer> queue2 = new ArrayBlockingQueue<Integer>(100);
    
    public void push(Integer data) {
    	queue1.add(data);
    }
    
    public Integer pop() {
    	if(queue1.size()<=0 &&queue2.size()<=0) {
    		try {
				throw new Exception("没有数据");
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    	if(queue1.size()==1) {
    		return queue1.poll();
    	}else if(queue1.size()>0) {
    		while(queue1.size()>1) {
    			queue2.add(queue1.poll());
    		}
    		return queue1.poll();
    	}else if(queue2.size()>0) {
    		while(queue2.size()>1) {
    			queue1.add(queue2.poll());
    		}
    		return queue2.poll();
    	}
    	return null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值