1

我有一个名为的类ListNode,它就像一个列表。使用这个类,我想建立一个杂志对象列表。在我的MagazineList课堂上,我想编辑 add 方法,因此当我插入Magazines 时,它们将按字母顺序排序。我怎样才能做到这一点?

我的ListNode班级:

    public class ListNode {
      private Object value;
      private ListNode next;

      //intializes node
      public ListNode (Object initValue, ListNode initNext) {
       value = initValue;
       next = initNext;
      }

    //returns value of node
    public Object getValue () {
      return value;
    }

     //returns next reference of node
    public ListNode getNext () {
       return next;
    }

     //sets value of node
    public void setValue (Object theNewValue) {
      value = theNewValue;
    }

    //sets next reference of node
    public void setNext (ListNode theNewNext) {
       next = theNewNext;
    }
   }

MagazineList班级的 add 方法:

    //when instantiated, MagazineList's  list variable is set to null
    public void add (Magazine mag) {

      ListNode node = new ListNode (mag, null);
      ListNode current;

      if (list == null)
         list = node;
      else {
         current = list;
         while (current.getNext() != null)
            current = current.getNext();
         current.setNext(node);
      }
   }

我用这个方法来比较类Magazines中的Magazine

 //compares the names (Strings) of the Magazines.
  public int compareTo(Magazine mag2) {
     return (title).compareTo(mag2.toString());
  }
4

2 回答 2

1

像这样

//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
    //assume that you have getTittle() method which returns Title
    return title.compareTo(mag2.getTitle());
}
于 2013-09-25T05:40:03.330 回答
1

一种简单的方法是保持列表始终排序。

然后,每次插入新节点时,从头开始,将新节点与列表中的每个节点进行比较,并在返回正数compareTo的节点之后插入新节点。compareTo

一个基本的实现可能是这样的。你需要改进它并考虑边缘情况等。

//when instantiated, MagazineList's  list variable is set to null
public void add (Magazine mag) {

   ListNode node = new ListNode (mag, null);
   ListNode current;

   if (list == null)
     list = node;
   else {
    current = list; // you list head
    while (node.compareTo(current) < 0)
       current = current.getNext();
   ListNode next = current.getNext();
   current.setNext(node);
   node.setNext(next);
   }
}
于 2013-09-25T05:45:07.517 回答