首页 > 解决方案 > 显示队列的元素

问题描述

我有一些问题要在 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

}

标签: javaqueue

解决方案


Andreas 的回答是首选和推荐的解决方案。但是,如果您不允许更新SimpleLinkedListQueue2<T>以下代码,则将标记偶数条目。唯一的问题是在和操作println期间的额外费用。当心,这个实现只是为了笑而写的,绝不能在野外使用。addremove

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

推荐阅读