【问题标题】:Ordering java linked list alphabetically (dictionary-like)按字母顺序排序java链表(类似字典)
【发布时间】:2015-06-19 09:41:34
【问题描述】:

我已经工作了好几个小时,试图按字母顺序排列字符串的链接列表(类似于字典)。给定的字符串仅为小写。 例如,输入:“hello my name is albert”将在列表中排序为:节点 1:albert, 节点2:你好, 节点 3:是, 等等。

到目前为止,我的代码读取了一个类似于上面示例的字符串并将其作为节点插入 - unordered

我在网上搜索了按字母顺序对链接列表进行排序的方法,并且性能良好,我发现 合并排序 很有用。 我已使用 compareTo() 将合并排序更改为适用于字符串,但我的代码在以下行中返回 nullPointerException 错误:

if(firstList._word.compareTo(secondList._word) < 0){

我正在寻求帮助来修复以下代码或其他按字母顺序对链表进行排序的方法(没有 Collection.sort)

我的完整代码是(在尝试添加合并排序以使用我的代码之后):

public class TextList
{
    public WordNode _head;

    public TextList() 
    {
    _head = null;
    }

    public TextList (String text)
    {
        this._head = new WordNode();
        int lastIndex = 0;
        boolean foundSpace = false;
        String newString;
        WordNode prev,next;
        if (text.length() == 0) {
            this._head._word = null;
            this._head._next = null;
        }
        else {
        for (int i=0;i<text.length();i++)
        {
                if (text.charAt(i) == ' ') {
               newString = text.substring(lastIndex,i);
               insertNode(newString);
               // Update indexes
                lastIndex = i;
                // set to true when the string has a space
                foundSpace = true;  
        }
    }
        if (!foundSpace) {
            //If we didnt find any space, set the given word
            _head.setWord(text);
            _head.setNext(null);

        }
        else {
            //Insert last word
            String lastString = text.substring(lastIndex,text.length());
            WordNode lastNode = new WordNode(_head._word,_head._next);
            _head.setNext(new WordNode(lastString,lastNode));

        }

        sortList(_head);

    }
}

      private void insertNode(String word)
      {
      //Create a new node and put the curret node in it
      WordNode newWord = new WordNode(_head._word,_head.getNext());
      //Set the new information in the head
      _head._word = word;
      _head.setNext(newWord);
    }

private WordNode sortList(WordNode start) {
        if (start == null || start._next == null) return start;
        WordNode fast = start;
        WordNode slow = start;
        // get in middle of the list :
        while (fast._next!= null && fast._next._next !=null){
            slow = slow._next; fast = fast._next._next;
        }
        fast = slow._next;
        slow._next=null;
        return mergeSortedList(sortList(start),sortList(fast));
        }

        private WordNode mergeSortedList(WordNode firstList,WordNode secondList){
            WordNode returnNode = new WordNode("",null);
            WordNode trackingPointer = returnNode;
            while(firstList!=null && secondList!=null){
                if(firstList._word.compareTo(secondList._word) < 0){
                    trackingPointer._next = firstList; firstList=firstList._next;
                }
                else {
                    trackingPointer._next = secondList; secondList=secondList._next
                    ;}
                trackingPointer = trackingPointer._next;
            }
            if (firstList!=null) trackingPointer._next = firstList;
            else if (secondList!=null) trackingPointer._next = secondList;
            return returnNode._next;
            }

        public String toString() {
            String result = "";
            while(_head.getNext() != null){
                _head = _head.getNext();
                result += _head._word + ", ";
            }
            return "List: " + result;
}


    public static void main(String[] args) {
        TextList str = new TextList("a b c d e a b");
        System.out.println(str.toString());
    }

}

【问题讨论】:

  • 您确定不想使用 Java 提供的实用程序吗?
  • “没有 Collection.sort”。为什么?
  • 双轴快速排序的平均排序时间非常快。

标签: java sorting linked-list mergesort


【解决方案1】:

在过去,我做了一个方法来按字母顺序对数组中的字符串进行排序作为学校硬件,所以嗯,这里是:

    private void sortStringsAlphabetically(){
    for (int all = 0; all < names.length; all++) {
        for (int i = all + 1; i < names.length; i++) {
            if (names[all].compareTo(names[i]) > 0) {
                String tmp = names[i];
                names[i] = names[all];
                names[all] = tmp;
            }
        }
    }
}

这段代码适用于数组,特别适用于名称数组。您可以调整它以使用列表,这非常简单,尤其是当我们考虑 List 接口中的各种方法及其所有实现时。

干杯。

【讨论】:

  • 那很好,我会尝试将其转换为链表。这段代码的性能(效率)如何?
  • 我不确定这段代码的大 O 表示法是什么,遗憾的是我无法计算它,但我认为它与不是最常见的选择排序大致相同地球上有效的排序方法....而且它似乎是 O(n^2) D:看看这里以找到迄今为止已知的 O 符号:bigocheatsheet.com
  • 是的,他使用数组的方式是 O(n^2),这很糟糕。我正在尝试使用 O(n) 将其转换为链表 .. 非常困难
  • 这肯定会很困难,我很想听听这个问题的解决方案:D 你可能想看看这里:blog.balfes.net/2010/09/14/… 它有不同排序算法的测试数据,但没有大O 符号数据 D:
【解决方案2】:

如果您不想拥有一个庞大的代码来获取单词的每个第一个字母并对其进行排序,请使用 Collection.sort() 来完成

我不知道 Collection.sort() 的问题是什么,所以使用它

这是一个简短的代码,正是你想要的:

String test = "hello my name is albert";
test = test.replaceAll(" ", "\n");
String[] te = test.split("\n");
List<String> stlist = new ArrayList<String>();
for(String st : te) {
    stlist.add(st);
}
Collections.sort(stlist);

【讨论】:

  • 我认为 OP 希望避免使用 sort 方法来了解它的工作原理,但这只是我 :-)
  • 我不能使用内置函数。这就是练习所说的
  • 至少你的练习清楚地表明了这一点......我们的老师要求我们的 CS 课对字符串数组进行排序(参见我帖子上的代码),一个人想出了 Arrays.sort(T[] array) xD 你应该已经看到老师的脸变得通红,当他在看解决方案时他的眼睛都快要飞出来了……嗯,现在回到主题。
【解决方案3】:

关于 NPE,你说这可能是因为你一开始在 head 中有一个空字符串,然后在 insert 方法中不断添加它。

this._head = new WordNode();

此外,添加最后一个元素也是不正确的。只需重复使用下面的插入方法

insertNode(text.substring(lastIndex,text.length()));

这些是我认为在将字符串转换为行列列表时遇到的问题

您可以使用下面的代码来处理第一个 null

private void insertNode(String word) {
    if (this._head == null) {
        this._head = new WordNode(word, null);
    } else {
        WordNode newWord = new WordNode(_head._word, _head.getNext());
        _head._word = word;
        _head.setNext(newWord);
    }
}

【讨论】:

  • 谢谢,insertNode的复用确实更好。但我不明白如何在第一次迭代时解决空头问题
  • 编辑答案以处理空值
  • 谢谢,但我注意到另一个问题。插入后,_head 变量指向最后一个节点。我不知道如何让它保持作为第一个节点的指针并使用另一个点来指向“当前”节点。你有什么想法吗?
  • 由于插入方法是在开始时插入节点,因此您的头节点始终指向插入的最后一个节点。当前方法中的 S 遍历节点,直到 next 为空。那是你的第一个节点。否则,您可以修改插入方法以在末尾插入新节点。
猜你喜欢
  • 2019-12-24
  • 2021-08-10
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多