【发布时间】:2020-06-20 17:47:29
【问题描述】:
我无法理解如何在链表中插入。我在网上找到了一些示例,但我似乎无法 100% 理解它。在这段代码中,我将 cmets 放在了我认为发生的事情上代码,以及我正在努力的。一些帮助将不胜感激。谢谢!
private static final class Node {
final Person person;
Node next;
Node(Person person) {
this.person = person;
}
}
public boolean insert(Person person) {
Node n = new Node(person);
//insert as the first element
if (head == null) {
head = n;
size++;
return true;
}
Node current = head;
Node prev = null;
int comparison;
while (current != null) {
//until the list is empty compare
comparison = person.name.compareTo(current.person.name);
//that person already exists
if (comparison == 0) {
return false;
} else if (comparison > 0) {
//if the next spot in the list is empty place the person there
if (current.next == null) {
current.next = n;
break;
}
} else {
//this is the part I dont understand
if (prev == null) {
Node oldHead = head;
head = n;
head.next = oldHead;
break;
}
//dont understand this either
prev.next = n;
n.next = current;
break;
}
//keep moving through the list
prev = current;
current = current.next;
}
size++;
return true;
}
【问题讨论】:
标签: java methods linked-list