2

我正在尝试实现一个单链表以在每个元素(名字、中间名、姓氏)中保存多个字符串值,以便我可以按排序并搜索元素中的不同字符串(按姓氏排序,搜索中间名, 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;
    }
} 
4

1 回答 1

5

I'm attempting to implement a singly linked list to hold multiple String values in each element (First, Middle, Last Name)

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> or List<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.

于 2012-10-22T16:56:02.407 回答