我正在尝试实现一个单链表以在每个元素(名字、中间名、姓氏)中保存多个字符串值,以便我可以按排序并搜索元素中的不同字符串(按姓氏排序,搜索中间名, ETC。)。
我创建了一个 Name 类来保存 3 个字符串(第一个、中间、最后一个)和每个字符串的观察者方法。
有人可以帮我修改我的 MergeSort 以按姓氏排序 (Name.getLastName()) 吗?如果我能弄清楚这一点,它应该让我走上正确的轨道来创建我的按中间名搜索方法。
提前致谢!
public class SinglyLinkedList {
private class Link {
public Name data;
public Link next;
Link(Name data)
{
this(data, null);
}
Link(Name d, Link n)
{
data = d;
next = n;
}
}
private Link first_;
// Creates an empty list
public void List()
{
first_ = null;
}
// Returns true iff this list has no items
public boolean isEmpty()
{
return first_ == null;
}
// Data is put at the front of the list
public void insertFront(Name data)
{
first_ = new Link(data, first_);
}
// Removes first element
public String removeFront()
{
Name data = first_.data;
first_ = first_.next;
return data;
}
public Link MergeSort(Link headOriginal)
{
if (headOriginal == null || headOriginal.next == null)
{
return headOriginal;
}
Link a = headOriginal;
Link b = headOriginal.next;
while ((b != null) && (b.next != null))
{
headOriginal = headOriginal.next;
b = (b.next).next;
}
b = headOriginal.next;
headOriginal.next = null;
return merge(MergeSort(a), MergeSort(b));
}
public Link merge(Link a, Link b)
{
Link temp = new Link();
Link head = temp;
Link c = head;
while ((a != null) && (b != null))
{
if (a.item <= b.item)
{
c.next = a;
c = a;
a = a.next;
}
else
{
c.next = b;
c = b;
b = b.next;
}
}
c.next = (a == null) ? b : a;
return head.next;
}
}