在Java中使用链接列表实现队列

在Java中使用链接列表实现队列

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

问题描述

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

 公共课程队列< T>实现LinkedList 
{
protected LinkedList< T>列表;

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

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

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




$ b $ p
$ b

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



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

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


解决方案

>队列<字符串> aQueue = new LinkedList< String>(); 那么你的 LinkedList 必须扩展/实现 Queue class / interface。请记住,超类可以是子类的对象引用实例,而不是反之。

  public class LinkedList< T>实现队列< T> {

class Node< T> {
T data;
节点< T>下一个;
}

//你在这里的所有行为
}



另外,正如Java文档所述,是一个界面,实现它。



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


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)

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

Queue<String> aQueue = new LinkedList<String>();
解决方案

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
}

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

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

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

08-05 01:21