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

题目:用两个栈实现一个队列。实现它的两个函数appendTail和deleteHead,分别完成队列尾部插入节点和在队列头部删除节点的功能。

下面是java代码:

package Stackqueue;

import java.util.Stack;

public class QueueWithTwoStacks {

	private Stack<Integer> stack1;
	private Stack<Integer> stack2;

	public QueueWithTwoStacks() {

		this.stack1 = new Stack<Integer>();
		this.stack2 = new Stack<Integer>();
	}

	public void appendTail(int[] a) {
		for (int i = 0; i < a.length; i++) {

			stack1.push(a[i]);
		}

	}

	public int deleteHead() {
		while (!stack1.isEmpty()) {
			int data = stack1.pop();
			stack2.push(data);

		}

		int number = stack2.pop();
		return number;
	}

	public static void main(String[] args) {

		int a[] = { 1, 2, 3, 4, 5, 6 };
		QueueWithTwoStacks queueWithTwoStacks = new QueueWithTwoStacks();
		queueWithTwoStacks.appendTail(a);
		System.out.println(queueWithTwoStacks.deleteHead());

	}

}

题目:用两个队列实现栈的功能,即pop函数和push函数

java代码:

package Stackqueue;

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

public class StackWithTowQueue {
	private Queue<Integer> queue1;
	private Queue<Integer> queue2;

	public StackWithTowQueue() {
		this.queue1 = new LinkedList<Integer>();
		this.queue2 = new LinkedList<Integer>();
	}

	public void push(int vaule) {//
		if (queue1.size() == 0 && queue2.size() == 0)
			queue1.add(vaule);
		if (queue1.size() != 0) {
			queue1.add(vaule);
		} else if (queue2.size() != 0) {
			queue2.add(vaule);
		}

	}

	public int pop() {
		if (queue1.size() == 0 && queue2.size() == 0)
			return 0;
		int re = 0;
		if (queue1.size() != 0 && queue2.size() == 0) {
			while (queue1.size() > 1) {
				re = queue1.remove();
				queue2.add(re);

			}
			re = queue1.remove();

		} else if (queue2.size() != 0 && queue1.size() == 0) {
			while (queue2.size() > 1) {
				re = queue2.remove();
				queue1.add(re);

			}
			re = queue2.remove();
		}

		return re;
	}

	public static void main(String[] args) {
		int a[] = { 1, 2, 3 };
		StackWithTowQueue stackWithTowQueue = new StackWithTowQueue();
		for (int i = 0; i < a.length; i++) {
			stackWithTowQueue.push(a[i]);

		}
		for (int i = 0; i < a.length; i++) {
			System.out.println(stackWithTowQueue.pop());

		}

	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值