【发布时间】:2011-10-25 11:50:32
【问题描述】:
我需要使用选择排序对链接列表进行排序。 但我不能使用集合。 我在查找最小元素和创建新版本的排序列表时遇到了麻烦。 谢谢。
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;
}
}
它发送添加的最大元素,如果我手动将“last”分配给“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 会是惯例
标签: java sorting linked-list