Three ways to achieve queue

Array implementation queue

//数组实现队列
class queue{
	int[] a = new int[5];
	int i = 0;
	//入队操作
	public void in(int m) {
		a[i++] = m;
	}
//	出队列操作   取出最前面的值  通过循环遍历把所有的数据向前一位
	public int out() {
		int index = 0;
		int temp = a[0];
		for(int j = 0;j < i;j++) {
			a[j] = a[j + 1];
		}
		return temp;
	}
	
}

ArrayList implements queue

//集合实现队列
class queue{
	List<Integer> list = new ArrayList<Integer>();
	int index = 0;
	
	public void in(int n) {
		list.add(n);
		index++;
	}
	//出队列操作
	//出队
    public int out(){  
       if(!list.isEmpty()){  
           index--;  
           return list.remove(0);  
       }  
       return -1;  
    }  
}

Two stack implementation queue

//两个堆栈实现一个队列
class queue3 {

  Stack<Integer> stackA = new Stack<Integer>();
  Stack<Integer> stackB = new Stack<Integer>();

  //入队
  public void in(int n) {
      stackA.push(n);
  }

  //出队  我们把A里面的元素遍历拿出放入B中 再拿出B中的第一个元素  
  public int out() {
	  //判断b栈有没有元素 有返回false 无返回真
      if(stackB.isEmpty()) {
    	  while(!stackA.isEmpty()) {
    		  stackB.push(stackA.pop());
    	  }
      }
      return stackB.pop();
  }

}

Guess you like

Origin blog.csdn.net/NuanShuTT/article/details/108573687