Java 中的泛型(队列) [英] Generics in Java (Queue)

查看:54
本文介绍了Java 中的泛型(队列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个堆栈类.

现在,我想基于该堆栈创建一个队列.像这样:

Now, i want to create a Queue based on that stack. Like this :

public class Queue<E> {

    private Stack<E> next;
    private Stack<E> next2;

    public E first() {
        
    }
    public Queue<E> enqueue(E e) {
        
    }
    public Queue<E> dequeue() {
        
    }
    public boolean isEmpty() {
        if (this.next == null) {
            return true;
        }
        if (Stack.isEmpty(next)) {
            return true;
        }
        return false;
    }

}

我不知道从哪里开始.我怎么解决这个问题?我的第一个想法是使用反向"方法.在堆栈中.但我不确定.

I don't know where to start. How can i solve this problem? My first ideas was to use the method "reverse" in Stack. But i'm not sure.

推荐答案

有两种方法可以做到这一点.第一个是使用您的函数 reverse 在堆栈末尾推送.像这样

There are 2 ways to do this. First one is to push at the end of stack using your function reverse. Like this

public class Queue<E> {

    private Stack<E> next;

    public E front() {
        return (E) Stack.<E>top(next);
    }
    public Queue<E> enqueue(E e) {
        Stack<E> nextNew = Stack.reverse(next);
        nextNew = Stack.push(nextNew, e);
        nextNew = Stack.reverse(nextNew);
        Queue<E> q = new Queue<E>();
        q.next = nextNew;
        return q;
    }
    public Queue<E> dequeue() {
        Stack<E> nextNew = Stack.pop(next);
        Queue<E> q = new Queue<E>();
        q.next = nextNew;
        return q;
    }
    public boolean isEmpty() {
        if (this.next == null) {
            return true;
        }
        if (Stack.isEmpty(next)) {
            return true;
        }
        return false;
    }
}

这篇关于Java 中的泛型(队列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆