栈和队列 互相实现

版权声明:转载请注明出处 https://blog.csdn.net/yrwan95/article/details/82879980

两个栈实现一个队列

import java.util.Stack;

// 用两个栈实现队列
public class MyStackToQueue {
	Stack<Character> s1 = new Stack<>();// 负责入列
	Stack<Character> s2 = new Stack<>();// 负责出列

	public void insert(char c) {
		s1.push(c);
	}

	public Character remove() {
		while (s2.isEmpty()) {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
		}
		return s2.pop();
	}

	public Character peek() {
		while (s2.isEmpty()) {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
		}
		return s2.peek();
	}
}

两个队列实现一个栈

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

//用两个队列实现栈
public class MyQueueToStack {
	Queue<Character> q1 = new LinkedList<>();
	Queue<Character> q2 = new LinkedList<>();// push时是暂存队列

	public void push(char c) {
		while (!q1.isEmpty()) {// 把q1的元素移动到q2
			q2.offer(q1.poll());
		}
		q1.offer(c);// 添加元素
		while (!q2.isEmpty()) {// 再移回来
			q1.offer(q2.poll());
		}
	}

	public Character pop() {
		return q1.poll();
	}

	public Character peek() {
		return q1.peek();
	}
}

猜你喜欢

转载自blog.csdn.net/yrwan95/article/details/82879980