我需要使用选择排序对链接列表进行排序。 但我不能使用集合。 我遇到了找到最小元素和创建排序列表的新版本的麻烦。 谢谢。选择排序双链表java
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;
}
}
它发出的加入最大元素,如果我手动assign'last“to'smallest”这是可行的。
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;
}
}
定义“不工作”。另外,如果这是一项任务,它应该被标记为家庭作业。 –
是“不工作”以什么方式? NPE不工作或随机返回不工作或什么?另外,是否有任何理由以相反顺序遍历列表?我觉得node.next会是约定 – SetSlapShot