当前位置:网站首页>Implement queue with stack

Implement queue with stack

2022-07-06 13:20:00 [email protected]

Realize the idea :

The queue is first in, first out (FIFO)

The stack is last in, first out (LIFO)

You need two stacks to realize the first in, first out of the queue

Stack in Realization push operation Stack out Realization pop operation

We push Advanced data will be pushed into the bottom of the stack , When we re push Into the stack in Data one by one pop Into the stack out when , Stack in The bottom element now becomes a stack out Top element , therefore pop We only need pop Stack out The data in the completion queue is first in first out (FIFO)

When joining the team, we need to judge the stack out Is it empty , If it's not empty , You need to pop Stack out Data in , If it is empty , All push Into the stack in

When leaving the team, we need to judge the stack in Is it empty , If it's not empty , You need to pop Stack in Data in , If it is empty , All push Into the stack out

The specific code is as follows :

// Stack simulation queue 
class MyQueue<E>{
	
	public Stack<E> in = new Stack<E>(); //  Join the team 
	public Stack<E> out = new Stack<E>();//  Out of the stack 
	
	
	//  The team 
	public void offer(E e) {
		while(!out.isEmpty()) {
			in.push(out.pop());
		}
		in.push(e);
	}
	
	//  Out of the team 
	public E poll() {
		while(!in.isEmpty()) {
			out.push(in.pop());
		}
		return out.pop();
		
	}
}

原网站

版权声明
本文为[[email protected] Yummy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916019988.html