I’m attempting to implement a singly linked list to hold multiple String values in each element (First, Middle, Last Name) so that I can sort by and search for different Strings in the element (Order by last name, Search for middle name, etc.).
I have created a Name class to hold 3 strings (first, middle, last) and observer methods for each string.
Can someone help me modify my MergeSort to sort by last name (Name.getLastName())? If I can get that figured out, it should put me on the right track to create my Search by middle name method.
Thanks in advance!
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;
}
}
Don’t. You’ve described a logical type – e.g. a
PersonalName– with three string members. So create that type as a separate type. Then you can use any of the normal built-in collections, e.g.Deque<PersonalName>orList<PersonalName>. (Is there any particular reason you need a linked list?)Any time you find yourself with a collection of values, always the same length, always with the same well-specified meaning for each value, strongly consider creating a type to encapsulate it.