几个月前我才刚开始编程,所以我收到了很多新信息,无法及时了解。因此在这里,我创建了我认为是排序后的链表,结果发现它没有排序
public boolean insert(Person person) {
Node n = new Node(person);
Node p = head;
if(p == null) {
head = n;
size++;
return true;
} else {
Node temp = p;
int comparison;
while(temp.next != null) {
comparison = temp.person.name.compareTo(person.name);
if(comparison == 0){
return false;
}
temp = temp.next;
}
temp.next = n;
size++;
return true;
}
}
该方法有效,它插入了人员,但是却没有按应有的方式对其进行排序。我需要更改/删除代码的哪一部分才能对其进行排序。
谢谢!
答案 0 :(得分:0)
您的else
部分出了问题。给定相同的值时,您将返回false
。但是对于有效的情况,并不能正确解释。
您需要具备以下条件。
答案 1 :(得分:0)
您应该这样插入:
static boolean insert(Person person) {
Node newNode = new Node(person);
if (head == null) {
head = newNode;
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) { /// greater than
if (current.next == null) { // check if reach tail of the linked list add and break
current.next = newNode;
break;
}
} else { // less then
if (prev == null) { // check if it should be first then put and break
Node oldHead = head;
head = newNode;
head.next = oldHead;
break;
}
prev.next = newNode;
newNode.next = current;
break;
}
prev = current;
current = current.next;
}
size++;
return true;
}