【问题标题】:Inserting elements into multi-linked list in ascending order将元素按升序插入到多链表中
【发布时间】:2016-06-09 15:20:02
【问题描述】:

我已经构建了一个由Friend 对象组成的多链表。 Friend 类具有 nameage 字段。我试图通过比较名称以升序插入Friend 对象,但我的代码中处理两个匹配名称的部分遇到了问题。

我要么得到空指针异常,要么打印的列表有问题。

填充列表

public static void main(String[] args) {
    LinkedList l = new LinkedList();
    l.add("Travis", 19);
    l.add("Kyler", 14);
    l.add("Abby", 10);
    l.add("Bob", 19);
    l.add("Travis", 12);
    l.add("Zander", 99);
    l.printList();
}

LinkedList类:

public class LinkedList {

    Friend head;
    int listcount;

    public LinkedList(){
        head = null;
        listcount = 0;
    }

    public void add(String name, int age){
        Friend node = new Friend(name,age);
        if(head==null){
            head = node;
            return;
        }
        if(head.name.compareTo(node.name) > 0){
            node.nextName = head;
            head = node;
            return;
        }
        Friend current = head;
        Friend previous = null;

        while(current.name.compareTo(node.name) < 0 && current.nextName != null){
            previous = current;
            current = current.nextName;
        }
        if(current.name.compareTo(node.name) == 0 && current.age < node.age){
            node.nextName = current.nextName;
            current.nextName = node;
        }
        previous.nextName = node;
        node.nextName = current;
    }
    public void printList(){
        Friend temp = head;
        while(temp!=null){
            temp.print();
            temp = temp.nextName;
        }
    }
}

Friend类:

public class Friend {
    String name;
    int age;
    Friend nextName;
    Friend nextAge;

    public Friend(String name, int age){
        this.name = name;
        this.age = age;
        nextName = null;
        nextAge = null;
    }

    public void print(){
        System.out.println(name+" "+age+". ");
    }
}

【问题讨论】:

  • 我认为第一个问题是Friend 不应该保持对下一个Friend 的引用。您应该为此创建一个Node 类并单独的职责
  • 我试图让Friend 充当Node 类。将两者分开可以让我做什么?
  • 如果一个类同时负责许多事情,则称为code smell/antipattern(不良代码设计的标志)。你应该分开职责
  • 我认为Node&lt;T&gt;(这里是Node&lt;Friend&gt;)是正确的方法。除此之外,我不知道如何建议修复错误......看起来你写了一个非常奇怪的链表......
  • 为什么不在名字上使用TreeMapComparator

标签: java algorithm sorting data-structures linked-list


【解决方案1】:

请像这样更改您的 add()(我的意思是您的 add() 方法的最后几行);

    if (current.name.compareTo(node.name) == 0 && current.age < node.age) {
        node.nextName = current.nextName;
        current.nextName = node;
    } else if (current.name.compareTo(node.name) < 0 ) {
        previous.nextName = current;            
        current.nextName = node;
    } else {
        previous.nextName = node;
        node.nextName = current;
    }

输出

艾比 10。 鲍勃 19. 凯勒 14. 特拉维斯 12. 特拉维斯 19. 赞德 99。

【讨论】:

  • 这适用于我在问题中使用的输入,但如果您只使用彼此相等的name 字符串,则会抛出null pointer exception。不过感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
相关资源
最近更新 更多