关于java链表上队列实现的线性时间和常数时间

时间:2017-01-03 04:41:33

标签: java algorithm queue

如果我保留the least added item的引用但不保留most recently added项的引用,那么我将有恒定的时间"dequeue"和线性时间"enqueue"。所以这是我在java链表中实现队列的程序。我想问一下这个程序是否同时保留了最少添加项目和最近添加的项目?所以当我"dequeue""enqueue"时,它都是恒定的时间?谢谢!

补充:我有点同意第一个回答所说的,所以我尝试了调试模式,它表明oldlast在最后一次更改后没有更新,所以它仍在工作......但是从我从uni学到的参考理论,就像他说的,它不应该工作..任何人都可以告诉我为什么它不会自动更新?(我的java版本1.8)

package tst;

public class linkedlsqueue {

    private class Node {
        String item;
        Node next;
    }

    Node first, last;

    public boolean isEmpty() {
        return first == null;
    }

    public void enqueue(String item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        if (isEmpty()) {
            first = last;
        }
        else {
            oldlast.next = last;
        }
    }

    public String dequeue() {
        String item = first.item;
        first = first.next;
        if (isEmpty()) {
            last = null;
        }
        return item;
    }



}

2 个答案:

答案 0 :(得分:2)

是的,你是对的。两种情况都是不变的。

最好为链接列表记录 firstlast
有人称之为headtail

如果您只维护lastfirst中的一个,则必须通过将first重复到last来寻找另一个,或者反之亦然,从而搜索另一个 - 一个元素,即O(n)。

就像你在黑暗中一样 你手握绳子的一端,你想知道它会导致什么。
我无法想到跟踪这条绳索的其他方法。需要O(n)来跟踪。

我更喜欢使用array [] 使用数组,就像你有一张地图,一个太阳和一个超级门户(随机访问)  但是,这不在问题的范围内。

答案 1 :(得分:1)

这个想法是正确的,但实施错误

看看这个:

public static class CustomKey {   
    ...
    @Override
    public int hashCode ()
    {
        // if you override equals, you should also override hashCode
    }

    @Override
    public boolean equals (Object other)
    {
        if (other == this)
            return true;
        if (!(other instanceof CustomKey))
            return false;
        CustomKey okey = (CustomKey) other;
        return this.topLevelId == okey.topLevelId && this.secondLevelId == okey.secondLevelId;
    }
    ...
}

当您执行create table IF NOT EXISTS department(deptid int, deptname(1) string, deptname(2) string) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile; 时,不要复制 public void enqueue(String item) { Node oldlast = last; last = new Node(); last.item = item; if (isEmpty()) { first = last; } else { oldlast.next = last; } } ,您只需将oldlast = last引用传递给last。< / p>

在整个过程中,last将是oldlast。与此同时,当您执行oldlast时,重置 last的值。

如果你只是想要入队,那么正确的方法可以这样工作:

last

要正确复制元素,你应该这样做:

last = new Node()
希望有所帮助。