使用栈实现队列结构、使用队列实现栈结构

使用栈实现队列结构

public static class stackToQueue{
		Stack<Integer> stack;
		Stack<Integer> help;
		
		public stackToQueue(){
			stack = new Stack<Integer>();
			help = new Stack<Integer>();
		}
		
		public void add(int num){
			stack.add(num);
		}
		//因为栈是先进后出,而队列是先进先出,所以只要将栈的值逐个保存到另一个栈,再弹出
		public int remove(){
			if(stack.empty()&&help.empty()){
				throw new ArrayIndexOutOfBoundsException();
			}else if(help.empty()){
				while(!stack.empty()){
					help.add(stack.pop());
				}
			}
			return help.pop();
		}
		
		public int peek(){
			if(stack.empty()&&help.empty()){
				throw new ArrayIndexOutOfBoundsException();
			}else if(help.empty()){
				while(!stack.empty()){
					help.add(stack.pop());
				}
			}
			return help.peek();
		}

	}

队列实现栈

public static class queueToStack{
		private Queue<Integer> queue;
		private Queue<Integer> help;
		
		
		public queueToStack(){
			queue = new LinkedList<Integer>();
			help = new LinkedList<Integer>();
		}
		
		public void add(int num){
			queue.add(num);
		}
		//因为是队列是先进先出,栈是先进后出,所以栈删除的时候会先删除最后一个进入的元素
		public int remove(){
			if(queue.isEmpty()){
				throw new ArrayIndexOutOfBoundsException();
			}
			while(queue.size()>1){
				help.add(queue.remove());
			}
			
			int res = queue.remove();
			swap();
			return res;
			
		}
		
		public int peek(){
			if(queue.isEmpty()){
				throw new ArrayIndexOutOfBoundsException();
			}
			while(queue.size()>1){
				help.add(queue.remove());
			}
			int res = queue.remove();
			help.add(res);
			swap();
			return res;
		}
		
		
		public void swap(){
			Queue<Integer> temp = queue;
			queue = help;
			help = temp;
		}
	}

猜你喜欢

转载自blog.csdn.net/liu_xiansen/article/details/82811202
今日推荐