双栈实现队列,双队列实现栈(java代码实现)

目录

栈和队列区别

两个队列实现栈

运行结果:

两个栈实现队列

运行结果:


栈和队列区别

数据结构里面的概念。

栈:先进后出

队列:先进先出

实现逻辑以及代码,如下(天才画手)

两个队列实现栈

实现栈的入栈功能:把所有数据都按顺序插入到queue1

实现栈的出栈功能:

1、除了queue1的最后一个数据,把其它所有数据都放入到队列queue2;

2、定义一个变量data存储这个“5”;

3、把queue2的所有数据再放回queue1,最后返回data。

import java.util.LinkedList;
import java.util.Queue;

public class TestTwo {
	public static void main(String[] args) {
		TwoQueue stack=new TwoQueue();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		stack.pop();
		stack.pop();
		stack.pop();
		stack.pop();
		stack.pop();
		stack.pop();
	}
}
class TwoQueue {

	 Queue<Integer> queue1= new LinkedList<Integer>();
	 Queue<Integer> queue2 = new LinkedList<Integer>();	 
	 
	 //数据放入
	 public void push(Integer value) {
		 queue1.offer(value);
		 System.out.println("入栈:"+value);
	 }
	 
	 //数据取出
	 public Integer pop() {
		 Integer data = null;
		 //队列1中的数据倒入队列2
		 while(!queue1.isEmpty()) {
			 data = queue1.poll();
			 if(queue1.isEmpty()) {
				 break;//队列1为空,结束
			 }
			 queue2.offer(data);
		 }
		 //数据倒回来
		 while(!queue2.isEmpty()) {			
			 queue1.offer(queue2.poll());
		 }
		 System.out.println("出栈:"+data);
		 return data;
	 }
}

运行结果:

两个栈实现队列

实现队列的入队功能:把所有数据都按顺序插入到stack1

实现队列的出队功能:

1、只需要一次转移操作,即把所有数据都从stack1转移到stack2;

2、此时从stack2 取数据,就已经实现目的了。

import java.util.Stack;

public class TestTwo {
	public static void main(String[] args) {
		TwoStack stack=new TwoStack();
		stack.add(1);
		stack.add(2);
		stack.add(3);
		stack.add(4);
		stack.add(5);
		stack.remove();
		stack.remove();
		stack.remove();
		stack.remove();
		stack.remove();
		stack.remove();
	}
}
class TwoStack {
	//定义两个栈
	Stack<Integer> stack1 = new Stack<Integer>();
	Stack<Integer> stack2 = new Stack<Integer>();
	
	//向队列中插入数据
	public void add(Integer num) {
		stack1.push(num);
		System.out.println("入队:"+num);
	}
		
	//数据出队列
	public Integer remove() {
		Integer re  = null;//输出的数据
		//如果第二个栈不为空:出栈
		if(!stack2.empty()) {
			re = stack2.pop();
		}else {
			//把栈1的数据放入栈2
			while(!stack1.empty()) {
				re=stack1.pop();
				stack2.push(re);
			}
			//把栈2的数据出栈
			if(!stack2.empty()) {
				re = stack2.pop();
			}
		}		
		System.out.println("出队:"+re);
		return re;
	}
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值