我遇到了一些困难。我想调整下面的这段代码,对Person类型的单链表进行排序。例如,我有:
class Person{
private String fn = "NN";
private String ln = "NN";
private Date dob = new Date(1, 1, 1970);
}
我想按名字、姓氏和出生日期对person的链表进行排序。同时,我已经给了一段代码来适应它,但我似乎找不到一个方法。任何帮助都将非常感激。下面是需要修改的代码:
public void sort() {
TextIO.putln("sorting...");
if (head == null)
return;
Node max, t, out = null, h = new Node();
h.next = head;
while (h.next != null) {
// display();
TextIO.putln("max=" + (max = findmax(h)).next);
t = max.next;
max.next = t.next;
t.next = out;
out = t;
}
head = out;
}
private Node findmax(Node h) {
char max = ' ';
Node maxNode = h;
for (Node tmp = h; tmp.next != null; tmp = tmp.next) {
if (tmp.next.data.c >= max) {
max = tmp.next.data.c;
maxNode = tmp;
}
}
return maxNode;
}
如果没有,详细的建议将非常有帮助,谢谢。请注意,我不能使用集合。排序或任何其他现成的函数,它必须实现。
谢谢
首先我想让你看看这个链接。它会让你了解Node类是如何实现的,以及如何实现list。
假设你从链接中阅读了内容,这里有一些评论;
public void sort() {
//this method does ascending sort of the list
TextIO.putln("sorting...");
if (head == null)
return;
Node max, t, out = null, h = new Node();
h.next=head; //make new list node let him point to beginning of the list(head)
while (h.next != null) { //until we get to the end of the list
// display();
TextIO.putln("max="+(max = findmax(h)).next);
//after findmax is finished we know reference
//to the node that contains max value
//and we need to bring that node to the beginning of the list
//that requires some reference rewiring
//first set t to point to next node from max
t = max.next;
//than max node will point to the next node from t
//this way max node becomes detached from list
max.next = t.next;
// now max node will point to some node that will represent new list head
// not new list just new list head
t.next = out;
out = t;
}
//after we complete sorting just point list head to the sorted list
head = out;
}
//find node that contains max value starting from some node
private Node findmax(Node h) {
//declare that max is null char
char max = ' ';
// set maxNode to be current node
Node maxNode = h;
//go through all nodes starting from current which is h
for (Node tmp = h; tmp.next != null; tmp = tmp.next) {
//if the data of some node in the list is bigger then our max value
if (tmp.next.data.c >= max) {
//then we are going to set that new value to be max
max = tmp.next.data.c;
// and set maxNode to be the node that has max value
maxNode = tmp;
}
}
return maxNode;
}
我的建议是看看提供的链接,并开始使用好的旧笔和纸。这是理解列表指针和节点的最佳方式。但是如果你不想用纸和笔你可以去这个链接它会给你展示基本列表操作的动画