按字母顺序排列的Java链接列表

时间:2015-07-13 04:29:58

标签: java string list insert

编辑: 对不起,这是我调用insert()方法的代码。无限循环现在消失了,但插入中的最后一个案例(否则......)仍然没有按顺序添加字符串。

public static void main(String[] args)
    {
        Frequency f = new Frequency();
        String s1 = "apple";
        String s2 = "crayon";
        String s3 = "bear";
        String s4 = "apple";
        String s5 = "";
        f.insert(s1);
        f.insert(s2);
        f.insert(s3);
        f.insert(s4);
        f.insert(s5);
        f.print();
    }

测试输出: (苹果,2)(蜡笔,1)

我在大学课程中收到了一个项目,要求我按字母顺序将字符串插入链接列表。我认为我有正确的方法,但运行程序会导致无限循环;我不确定为什么。这是我到目前为止的代码,我更喜欢对代码的解释:

/*
 * Inserts a word into the linked list. If the word exists, increment the 
 * count by q. 
 */
public void insert(E word){
    //word is empty
    if(word.equals("")){
        return;
    }
    //list is empty
    else if(isEmpty())
    {
        Node n = new Node(word);
        first = n;
        N++;
    }
    //list already has word
    else if(contains(word))
    {
        Node cur = first;
        while(cur != null)
        {
            if(cur.key == word)
                cur.count++;
            cur = cur.next;
        }
    }
    //list only has 1 object
    else if(N == 1)
    {
        Node n = new Node(word);
        first.next = n;
        N++;
    }
    //inserting new object
    else
    {
        Node n = new Node(word);
        Node cur = first;
        while(cur != null)
        {
            if(cur.next != null)
            {
                if(cur.next.key.compareTo(word) <= 0)
                {
                    Node temp = cur.next;
                    cur.next = n;
                    n.next = cur.next;
                    return; //exit, since the word has been added
                }
                cur = cur.next;
            }
            else
                cur.next = n;
        }
        N++;
    }
}

1 个答案:

答案 0 :(得分:0)

正如我所知,您希望以正确的顺序获得Keys和所有Keys的数量,您可以使用

TreeMap<String,Integer>

为了您的目的并插入:

treeMap.put(key, treeMap.getOrDefault(key, 0));

问题: 如果你在问题的最后一个案例中,“cur”永远不会为空。 因为只有当cur.next!= null时才改变cur变量。所以一旦cur.next为null,你就会期望在下一轮之后while会中断。但是你不再改变cur的值了。

    while(cur != null)
    {
        if(cur.next != null)
        {
            if(cur.next.key.compareTo(word) <= 0)
            {
                Node temp = cur.next;
                cur.next = n;
                n.next = cur.next;
                return; //exit, since the word has been added
            }
            ---> old position of cur = cur.next;
        }
        else {
            cur.next = n;
        }
        cur = cur.next; ---> move it here
    }