Java中使用链表实现的队列

Queue using linked list implementation in Java(Java中使用链表实现的队列)

本文介绍了Java中使用链表实现的队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很快用Java写了一个链表类.我想编写另一个使用链表的队列类.我将如何在 Java 中实现这一点?我不完全理解 implements/extends 关键字......这就是我的队列的样子(例如):

I quickly wrote a linked list class in Java. I want to write another queue class which uses the linked list. How would I achieve this in Java? I don't fully understand the implements / extends keywords... this is what my queue looks like ( for example):

public class Queue<T> implements LinkedList
{
    protected LinkedList<T> list;

    public Queue() {
        list = new LinkedList<T>();
    }

    public void add( T element) {
        list.add( element);
    }

    public T removeLast() {
        return list.removeLast();
    }   
}

还要注意,链表类也是通用的.我知道已经有内置类来实现此功能,但我想学习(这就是我尝试手动执行此操作的原因)

Also note that the linked list class is also generic. I know there are already built in classes to achieve this functionality, but I wanted to learn ( which is why I am trying to do this manually)

另外,最后,我希望能够这样说:

Additionally, in the end, I would like to be able to say something like this:

Queue<String> aQueue = new LinkedList<String>();

推荐答案

如果你想要像 Queue 这样的行为aQueue = new LinkedList(); 那么你的 LinkedList 必须扩展/实现 Queue 类/接口.请记住,超类可以是子类的对象引用实例,反之亦然.

If you want a behavior like Queue<String> aQueue = new LinkedList<String>(); then your LinkedList must extend/implement the Queue class/interface. Remember that a super class can be the object reference instance of a sub class, not viceversa.

public class LinkedList<T> implements Queue<T> {

    class Node<T> {
        T data;
        Node<T> next;
    }

    //all your behavior here
}

此外,正如 Java 文档所述,Queue 是一个接口和 LinkedList 实现它.

Also, as the Java documentation states, Queue is an interface and LinkedList implements it.

注意:如果你想使用你的 LinkedList 实现一个队列,你应该看到@Tudor 发布的代码示例.

Note: If you want to implement a Queue using your LinkedList, you should see the code sample posted by @Tudor.

这篇关于Java中使用链表实现的队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java中使用链表实现的队列

基础教程推荐