必须按字母顺序从链接列表中对txt文件中的单词进行排序和显示。我怎么做?

时间:2016-10-08 04:41:47

标签: java sorting

WordLinkMenu.java

这是来自构建文本文件的程序的主类和菜单。

public void build() throws Exception
{
    Scanner infile = new Scanner(new File("dictionary.txt"));
    int level = 0;

    while(infile.hasNext()){
        if(infile.hasNextInt())
        {
            level = infile.nextInt();
            infile.nextLine();
        }
        else
        {
            String[] words = infile.nextLine().split(" ");
            for (int i=0; i < words.length; ++i)
            {
                dictionary.insertWord(words[i], level);
            }
        }
    }
    infile.close();
}

这是用户插入新单词进入节点并尝试按字母顺序显示的地方。

ListOfNodes.java

public boolean insert(DictionaryNode node)
{
    if (head != null)
    {
        DictionaryNode lastWord = head;
        DictionaryNode word = head;

        //change heads
        if(word.getWord().compareTo(node.getWord()) > 0 )
        {
            node.setNextNode(head);
            head = node;
            nodeCount++;
            return true;
        }

        for (int i = 0; i < nodeCount; ++i)
        {
            if (word.getWord().compareTo(node.getWord()) == 0)
            {
                //Word exists in dictionary
                return false;
            }
            else if (word.getWord().compareTo(node.getWord()) < 0)
            {
                //get next node
                lastWord = word;
                word = word.getNext();
            }
            else 
            {
                lastWord.setNextNode(node);
                //greater than 0
                //add word and set next nodes here

                //if not last node set next
                if (nodeCount != i)
                {
                    node.setNextNode(word);
                }
                nodeCount++;
                return true;
            }
        }
    }
    else
    {
        head = node;
        nodeCount++;
    }

    //no errros
    return true;
}   

这将显示文本文件中的数据

Dictionary.java

public void display()
{
    for(int i=0; i <= 25; ++i)
    {
        if (data[i] != null)
        {
            int num = data[i].getNodeCount();
            DictionaryNode node = data[i].getHead();
            for (int j=0; j < num; ++j)
            {
                System.out.print(node.getWord() + " ");
                node = node.getNext();
            }
            System.out.println();
        }
    }
}

0 个答案:

没有答案