这更多是因为我缺乏理解 SortedList 类的能力。我理解的 ListNode:它是一个由两件事组成的节点:一个可比较的对象和一个 ListNode 对象,它本身具有相同的两件事。
我不明白下面的 SortedList 类中的插入和删除方法是如何工作的。理解起来非常复杂。在 SortedList 类中,如果 head 为 null,则指向 curr。curr 不应该为空吗?那么while循环不应该执行,但实际上当我使用println测试执行时它确实执行了。
ListNode 类的代码:
public class ListNode {
private Comparable data;
private ListNode next;
public ListNode() {
data = null;
next = null;
}
public ListNode(Comparable x) {
data = x;
next = null;
}
public ListNode(Comparable x, ListNode nextListNode) {
data = x;
next = nextListNode;
}
public Comparable getData() {
return data;
}
public ListNode getNext() {
return next;
}
public void setData(Comparable x) {
data = x;
}
public void setNext(ListNode nextListNode) {
next = nextListNode;
}
}
排序列表的代码:
public class SortedList {
private ListNode head;
public SortedList() {
head = null;
}
public void insert(Comparable x) {
ListNode curr = head, prev = null;
while (curr != null && x.compareTo(curr.getData()) > 0) {
prev = curr;
curr = curr.getNext();
}
if (prev == null) {
head = new ListNode(x, curr);
} else {
prev.setNext(new ListNode(x, curr));
}
}
public boolean delete(Comparable x) {
if (head == null) {
return false;
}
ListNode curr = head, prev = null;
while (curr != null && x.compareTo(curr.getData()) > 0) {
prev = curr;
curr = curr.getNext();
}
if (curr == null || x.compareTo(curr.getData()) != 0) {
return false;
}
if (prev == null) {
head = curr.getNext();
} else {
prev.setNext(curr.getNext());
}
return true;
}
public void output() {
for (ListNode curr = head; curr != null; curr = curr.getNext()) {
System.out.println(curr.getData());
}
}
}
TestSortedList 的代码:
public class TestSortedList {
public static void main(String[] args) {
SortedList list = new SortedList();
list.insert(5);
list.insert(1);
list.insert(10);
list.insert(3);
list.insert(7);
list.output();
System.out.println(list.delete(5));
System.out.println(list.delete(5));
System.out.println(list.delete(1));
System.out.println(list.delete(10));
System.out.println(list.delete(11));
}
}