我正在尝试另一种方法来对链表进行排序。除了可用的方法之外,我决定将链表中的每个节点放在一个数组中,这样我就可以很容易地比较数据变量。我在数组上应用了quickSort,这就是我的got...however,当结果显示时,我得到的是节点的内存地址,而不是学生信息
这就是显示的内容:(作为输出)
排序列表为:
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();
}
}发布于 2013-11-01 18:45:03
.however,当结果显示时,我得到的是节点的内存地址,而不是学生信息
因为您没有覆盖Node类中的toString方法,所以要打印Object类中定义的此方法的默认行为:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}首先,您必须覆盖Student类中的toString方法:
@Override
public String toString (){
return this.id+"-"+this.name+"-"+this.age+"-"+this.country+"-"+this.year;
}然后,您可以覆盖Node类中的toString方法:
@Override
public String toString (){
return this.student.toString();
}然后让你的for像这样循环。
或者只是覆盖学生类中的toString方法:
并修改for循环,如下所示:
for(int q =0;q<n.length;q++){
System.out.println(n[q].getStudent() + " ");
}发布于 2013-11-01 19:47:17
我已经修复了这个问题并对数组进行了排序,
我的quickSort方法中有一个问题..对于索引,它应该是:
int index = partition(arr,left,right)而不是:
int index = partition(arr, left, right-1);正如ZouZou之前指出的,for循环有问题,所以我也修复了它
非常感谢你的帮助!
https://stackoverflow.com/questions/19725175
复制相似问题