今天就跟大家聊聊有关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实现队列的方法有哪些有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。