Java 用两个队列实现一个栈

本文介绍了如何利用Java通过两个队列来实现栈的功能,并特别讨论了如何进行栈的元素翻转,例如将输入的1 2 3 4 5 6 转换为输出6 5 4 3 2 1。主要思路包括数组翻转的想法,每次在空队列尾部插入元素,然后在需要时反转队列。该方法利用链表数组避免了预设长度的问题。

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

比如我要去实现一个1 2 3 4 5 6 通过两个队列去输出6 5 4 3 2 1.
思想:
一.数组翻转的思想。
二.每次都在空的一端插入,插入完把旧队列反转过来,以此循环
三.使用链表数组来表示队列,可以不用考虑初始化长度。
刚开始插入1.

1

插入2

12

插入3

321

插入4

1234

插入5

54321

插入6

123456
import java.util.LinkedList;

/**
* @author zhangrichao
* @version 创建时间:2019年1月23日 下午4:01:49
* 用两个队列实现一个栈
*/
public class QueueToStack {
	LinkedList<Integer> queueA=new LinkedList<Integer>();  
    LinkedList<Integer> queueB=new LinkedList<Integer>();  
     //模仿栈的入栈操作
    public void push(int value)  
    {  
    	if(queueA.isEmpty()&&queueB.isEmpty()){
    		queueA.addLast(value);
    	}else if(queueA.isEmpty()&&!queueB.isEmpty()){
    		queueA.addLast(value);
    		transfer();
    	}else if(queueB.isEmpty()&&!queueA.isEmpty()){
    		queueB.addLast(value);
    		transfer();
    	}
    }  
    //模仿栈的出栈操作  必须是非空的栈才能出栈啊  
    public int pop()
    {  
       if(queueA.isEmpty()&&!queueB.isEmpty()){
    	  return queueB.removeFirst();
       }
       else if(queueB.isEmpty()&&!queueA.isEmpty()){
    	   return queueA.removeFirst();
       }
       else{
    	   return 0;
       }
    }  
    //将旧队列反转放在插入头元素的位置上
    public void transfer()
    {  
    	 //因为默认从队列A插入。所以后面第二个数插入队列B时。要默认B为优先条件,毕竟两个队列的尺寸都为1
    	 if(queueB.size()==1&&!queueA.isEmpty()){
         	while(!queueA.isEmpty()){
         		int element=queueA.removeFirst();
         		queueB.addLast(element);
         	}
         }
    	 
         if(queueA.size()==1&&!queueB.isEmpty()){
        	while(!queueB.isEmpty()){
        		int element=queueB.removeFirst();
        		queueA.addLast(element);
        	}
        }
       
    }  
    public static void main(String[] args)  
    {  
        QueueToStack stack=new QueueToStack();  
        stack.push(1);  
        stack.push(2);  
        stack.push(3);  
        stack.push(4);  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        stack.push(5);  
        stack.push(6);  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop()); 
    } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值