java - 显示队列的元素
问题描述
我有一些问题要在 java 中显示队列列表的元素,而不会从 add 方法中显示出来。我需要打印队列列表中的偶数
package ru.vsu.cs.course1;
public class SimpleLinkedListQueue2<T> implements SimpleQueue<T> {
private class ListNode<T> {
public T value;
public ListNode<T> next;
public ListNode(T value, ListNode<T> next) {
this.value = value;
this.next = next;
}
}
private ListNode<T> head = null;
private ListNode<T> tail = null;
private int count = 0;
@Override
public void add(T value) {
ListNode<T> newNode = new ListNode<>(value, null);
if (count > 0) {
tail.next = newNode;
} else {
head = newNode;
}
tail = newNode;
count++;
System.out.println(value);
}
@Override
public T remove() throws Exception {
if (count == 0) {
throw new Exception("Queue is empty");
}
T value = head.value;
head = head.next;
count--;
if (count == 0) {
tail = null;
}
return value;
}
@Override
public T element() throws Exception {
if (count == 0) {
throw new Exception("Queue is empty");
}
return head.value;
}
public class main {
public static void main(String[] args) {
SimpleLinkedListQueue2<Integer> queue2=new SimpleLinkedListQueue2<Integer>();
queue2.add(67);
queue2.add(54);
queue2.add(75);
queue2.add(100);
System.out.println("--------------");
}
}
driver code
}
解决方案
Andreas 的回答是首选和推荐的解决方案。但是,如果您不允许更新SimpleLinkedListQueue2<T>
以下代码,则将标记偶数条目。唯一的问题是在和操作println
期间的额外费用。当心,这个实现只是为了笑而写的,绝不能在野外使用。add
remove
public static void printEven(SimpleLinkedListQueue2<Integer> queue) throws Exception {
SimpleLinkedListQueue2<Integer> tempQ = new SimpleLinkedListQueue2<Integer>();
while (true) {
try {
queue.element();
} catch (Exception e) {
break;
}
Integer tempInt = queue.remove();
if (tempInt%2 == 0) {
System.out.println("even: " + tempInt.toString());
}
tempQ.add(tempInt);
}
while (true) {
try {
tempQ.element();
} catch (Exception e) {
break;
}
queue.add(tempQ.remove());
}
}
这里的逻辑是弹出头部,读取并评估是否为偶数,将其推入临时队列,然后恢复原始队列。输出将是:
67
54
75
100
--------------
67
even: 54
54
75
even: 100
100
67
54
75
100
推荐阅读
- java - 使用 return vs While(condition) 方法来打破循环
- python - 如何在相同坐标上转动蛇段?
- spring - 在 Spring Boot 和 Hibernate 中使用 HikariCP 时可能出现 SQL Too many connections 问题的可能情况有哪些?
- php - Preg_split 创建一个数组,但使其为空
- machine-learning - 线性回归中最小化成本函数的遗传算法
- python - 如何循环和迭代将多个 csv 文件导入 AWS 存储桶?
- python - 为什么y轴的增量为1而不是90
- r - R中的数据透视表,一天中的每个小时都有一列
- python - 无法在 mininet 中使用 ping6
- azure-ad-b2c - 当有多种用户帐户类型时,有多少个用户存储?