使用insert方法对链表进行排序

这是我的代码,出于练习和教学目的,我想知道如何按升序插入。例如,我输入了Andy,Berta,Aaron;输出应为Aaron,Andy,Berta。我需要对我的代码进行哪些更改才能使这一点变得不重要。谢谢!

public boolean insert(Person person) {

    Node n = new Node(person);

    if (head == null) {
        head = n;
        size++;
        return true;
    }

    Node current = head;
    Node prev = null;
    int comparison;

    while (current != null) {
        comparison = person.name.compareTo(current.person.name);
        if (comparison == 0) {
            return false;
        } else if (comparison > 0) { 

            if (current.next == null) { 
                current.next = n;
                break;
            }
            current = current.next;
        } else { 
            if (prev == null) { 
                Node oldHead = head;
                head = n;
                head.next = oldHead;
                break;
            }
            prev.next = n;
            n.next = current;
            break;
        }
        prev = current;
        current = current.next;
    }
    size++;
    return true;
}
评论