Java实现队列 Java实现队列的三种方法集合

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java实现队列 Java实现队列的三种方法集合

颜颜颜颜颜越   2021-03-16 我要评论
想了解Java实现队列的三种方法集合的相关内容吗,颜颜颜颜颜越在本文为您仔细讲解Java实现队列的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,队列,下面大家一起来学习吧。

数组实现队列

//数组实现队列
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实现队列

//集合实现队列
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; 
  } 
}

两个堆栈实现队列

//两个堆栈实现一个队列
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();
 }
}

补充知识:java使用链表实现队列

队列使用Java进行链表实现,在网上找到了一张图,很好,借鉴一下

设置两个结点node,front指向队首元素,rear指向队尾;

上代码:

 public class LinkedQueue {
 
  Node front;//队头指针,指向队头节点
  Node rail;//队尾指针,指向队尾节点 
  int size = 0;//记录队列长度 
 
  //构造函数
  public LinkedQueue() {
    front = rail = null;
  }
 
  public boolean isEmpty() {
    return size == 0 ? true : false;
  }
 
  //添加元素
  public boolean addQueue(Object ele) {
    if (size == 0) {
      front = new Node(null, ele);
      rail = front;
      size++;
      return true;
    }
    Node s = new Node(null, ele);
    //这块有个主意的地方,一旦rail设置了next属性,因为front节点与rail节点指向了同一个node节点,持有同一个结点的一个引用,因此front节点next属性也被填充
    rail.setNext(s);
    rail = s;
    size++;
    return true;
  } 
 
  /**
   * 删除元素,出队列
   * @return
   */
  public boolean deleteQueue() {
    if (isEmpty()) {
      System.out.println("当前队列为空");
      return false;
    } 
    front = front.next;
    size--;
    return true; 
  } 
 
  public static void main(String[] args) {
    LinkedQueue queue = new LinkedQueue();
 
    queue.addQueue(1);
    queue.addQueue(2);
    queue.addQueue(3);
    queue.deleteQueue();
 
  } 
}
 
/**
 * 首先链表底层是一个个结点
 */
class Node {
 
  Node next;
  Object element;
 
  public Node(Node next, Object element) {
    this.next = next;
    this.element = element;
  }
 
  public Node getNext() {
    return next;
  }
 
  public void setNext(Node next) {
    this.next = next;
  }
 
  public Object getElement() {
    return element;
  }
 
  public void setElement(Object element) {
    this.element = element;
  }
 
}

以上这篇Java实现队列的三种方法集合就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们