我正在尝试另一种方法来对链表进行排序。除了可用的方法之外,我决定从链表中取出每个节点并将其放在一个数组中,这样我就可以轻松地比较数据变量。我在数组上应用了快速排序,这就是我得到的......但是,当显示结果时,我得到的是节点的内存地址而不是学生信息
这就是出现的内容:(作为输出)
排序列表为:
homework2.Node@44b471fe
homework2.Node@22a7fdef
homework2.Node@431067af
homework2.Node@6a07348e
null
这是我的代码。
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
Student s = new Student(1, "John", 20, "Italy", "2011");
list.addStudent(s);
Student s2 = new Student(2, "Mark", 19, "UAE", "2010");
list.addStudent(s2);
Student s3 = new Student(3, "Sally", 35, "UAE", "2000");
list.addStudent(s3);
System.out.println("Students in the list: ");
list.print();
Node[] n = list.convertA(list);
quickSort(n, 0, (n.length-1));
System.out.println("Sorted list is:");
for(int q =0;q<n.length;q++){
System.out.println(n[q] + " ");
}
}
public static int partition(Node arr[], int left, int right) {
int i = left, j = right;
Node tmp;
Node pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i].getStudent().getAge() < pivot.getStudent().getAge()) {
i++;
}
while (arr[j].getStudent().getAge() > pivot.getStudent().getAge()) {
j--;
}
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
public static void quickSort(Node arr[], int left, int right) {
int index = partition(arr, left, right-1);
if (left < index - 1) {
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(arr, index, right);
}
}
Node类如下:
public class Node {
private Student student;
public Node link;
public Node() {
student = null;
link = null;
}
public Node(Student s) {
student = s;
}
public Node(Student s, Node l) {
student = s;
link = l;
}
public Object getData() {
return student.toString();
}
public Student getStudent() {
return student;
}
public void setLink(Node link) {
this.link = link;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public String toString() {
return this.student.toString();
}
}