我需要使用Selection排序对链接列表进行排序。 但是我不能使用Collections。 我在查找最小元素和创建新版本的排序列表时遇到了麻烦。 谢谢。
public class LinkedList {
public Node first;
public Node last;
public LinkedList() {
first = null;
last = null;
}
public boolean isEmpty() {
return first == null;
}
public void addFirst(Student student) {
Node newNode = new Node(student);
if (isEmpty())
last = newNode;
else
first.previous = newNode;
newNode.next = first;
first = newNode;
}
public void addLast(Student student) {
Node newNode = new Node(student);
if (isEmpty())
first = newNode;
else
last.next = newNode;
newNode.previous = last;
last = newNode;
}
public void display() {
Node current = last;
while (current != null) {
System.out.print(current.student.name + "\b");
System.out.print(current.student.surname + "\b");
System.out.println(current.student.educationType);
current = current.previous;
}
}
由于无效findSmallest
方法Sort
方法无法正常工作。我尝试通过创建一个新列表来实现排序,其中我以有序的方式放置节点。而且它也没有走出“While循环”
public void Sort() {
LinkedList list = new LinkedList();
Node toStart = last;
while (toStart!=null){
list.addLast(findSmallest(toStart).student);
toStart = toStart.previous;
}
}
它发送了最大的元素,如果我手动将'''分配给最小的',它就会起作用。
public Node findSmallest(Node toStartFrom) {
Node current = toStartFrom;
Node smallest = toStartFrom; //if i put here `last` it will work correctly
while(current != null) {
if (smallest.student.name.compareToIgnoreCase(current.student.name) > 0) smallest = current;
current = current.previous;
}
return smallest;
}
}
public class Node {
public Student student;
public Node next;
public Node previous;
public Node(Student student) {
this.student = student;
}
}
public class Student {
public String name;
public String surname;
public String educationType;
static public Student createStudent() {
....
return student;
}
}
答案 0 :(得分:1)
没有双向链表可能会有所帮助,因为您需要维护的链接较少。您也可能遇到findSmallest()方法的问题,因为您最初将当前和最小设置为同一节点,因此当if(smallest.student.name.compareToIgnoreCase(current.student.name)> 0)语句为执行时,您正在将学生的姓名与学生的姓名进行比较。例如,如果将最小的节点设置为具有John well current的学生姓名,则将其设置为相同的节点,因此当前的学生姓名也是John。如果他们是具有相同名称的不同学生但在您的代码中他们是同一个学生并且当前和最小指向同一节点,则不是问题。实际上,这个if语句总是错误的,你永远不会执行代码来沿列表移动当前。这也是为什么当你设置tiny = last时,该方法至少在某些时候起作用。
答案 1 :(得分:0)
如上所述,尝试类似
的内容 smallest = startnode
next =startnode.next
while(next != null)
compare next with smallest, and assign accordingly
next = next.next
不应该太难将其变成代码