将队列元素添加到另一个队列

时间:2018-07-26 20:05:40

标签: java interface queue temp

因此,我添加了此条件,以将元素添加到变量temp中,并通过递归循环运行它,但是它给出了一条错误消息,如果队列为空,则会显示该错误消息NoSuchElementException。创建另一个Queue而不是temp并在其中以其他方式放置元素会更容易吗?

 public QueueInterface<T> reverseQueue() {
    T temp = dequeue();
    Queue<T> a = new Queue<T>();
    if (a.isEmpty()) {
        temp = dequeue();
        a.enqueue(temp);
        reversed();
    }
    Stack<T> b = new Stack<T>();
    while(!a.isEmpty()){
        b.push(a.dequeue());
    }
    while(!b.isEmpty()){
        a.enqueue(b.pop());
    }
    return a;
}

  public Queue(Queue<T> other) { //creates shallow copy
    int i = 0;
    while (!other.isEmpty() && i < other.size()) {
        this.enqueue(other.peek());
        other.enqueue(other.dequeue());
        i++;
    }
}


  public T dequeue() throws NoSuchElementException {
    if (isEmpty()) {
        throw new NoSuchElementException();
    }
    else {
        nElems--;
        T element = front.getData();
        front = front.getNext();
        if (front == null) {
            rear = null;
        }
        return element;
    }
}

0 个答案:

没有答案