【问题标题】:Using listIterator to add objects alphabetically to a linked list使用 listIterator 按字母顺序将对象添加到链表
【发布时间】:2015-04-12 21:42:07
【问题描述】:

我正在尝试按字母顺序将字符串添加到链接列表中。一切正常,除了当我在迭代器对象上调用 add() 方法时,它将字符串 after 添加到当前迭代器位置而不是之前,从而打乱了我的字母顺序。

有没有办法让它在迭代器的当前位置之前添加对象?

提前致谢, 泰勒

附言似乎其他堆栈溢出的问题完全相反,很奇怪。

 //addElement method, adds string to the linked list in alphabetical order
 public void addElement(Object obj)
 {
   String inString = (String) obj;
   iter = listIterator();
   Node newNode = new Node();
   newNode.data = obj;

   if (first != null)
   {
       int checker = 0;
       while (iter.hasNext()==true && checker == 0)
       {
           String testString = (String) iter.next();
           int i = inString.compareTo(testString);
           if (i <= 0)
           {
               iter.add((Object) inString);
               checker++;
           }

       } 

       if (checker == 0)
           iter.add((Object) inString);

   }

   else
   {
       //iter.add((Object) inString);
       addFirst((Object) inString);
   }
}

【问题讨论】:

    标签: java linked-list alphabetical listiterator


    【解决方案1】:

    这是一种非常低效的排序方式。尝试改用排序功能。如果您必须进行插入,则不要使用列表迭代器 - 保留您正在查看的位置的索引并使用 add(index, value) 版本的 add - https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#add(int,%20E)

    您还可以在迭代器上使用previousIndex() https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#previousIndex() 来查找要插入的索引,以便之前插入。这不太可能让你开心。

    【讨论】:

    • 感谢您的快速回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多