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

时间:2021-05-20

数组实现队列

//数组实现队列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实现队列的三种方法集合就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章