繁体   English   中英

按字母顺序将新对象按顺序插入到(字符串的)Linkedlist中

[英]Inserting new object onto Linkedlist(of Strings) in alphabetical order without sorting

我想知道在Java中是否可行。 我想按字母顺序将其插入正确的位置。 例如,LinkedList的元素(被称为coollist)是:[Dusty,Gordon,Mayer,Popovic,Zechariah],我尝试通过执行以下操作插入另一个String:

    coollist.add(d,Nyugen); //d is a a variable representing ant int which is the index

无论LinkedList中包含什么,我如何使d值按字母顺序插入? 你们能帮我吗? 我希望这是有道理的。

您可以遍历列表,搜索索引何时生成大于参数的字符串。 然后只需在该索引后面插入即可。 如果这是一个单向链接列表,则必须跟踪上一个节点,以便可以更新其字段。

    Node newNode = new Node( stringToBeAdded ); //Create new node

    if ( this.head == null ){ //list is empty, just insert
      this.head = newNode; //Initialize head
    }

    else{

      Node cur = this.head; //Start at the beginning of the list
      Node prev = this.head; //just initialize the previous node to something

      //keep going until found or at end of list
      while( (stringToBeAdded < cur.data) && (cur != null) ){ 
        prev = cur;
        cur = cur.next;
      }

      prev.next = newNode;

      if ( cur != null ){ //if we did not reach the end
        newNode.next = cur; //current Node is alphabetically greater
      }
    }

以下是在LinkedList中找到排序索引的一种方法。

import java.util.*;

public class SortedLinkedListDemo {

public static void main (String [] args) {
    List<String> list = new LinkedList<String> ();
    list.add ("Dusty");
    list.add ("Gordon");
    list.add ("Mayer");
    list.add ("Popovic");
    list.add ("Zechariah");

    list.add (getSortedIndex ("Nyugen", list), "Nyugen");

    System.out.println ("List: "+list);
}

private static int getSortedIndex (String name, List<String> list) {
    for (int i=0; i < list.size(); i++) {
        if (name.compareTo(list.get(i)) < 0) {
            return i;
        }
    }       
    // name should be inserted at end.
    return list.size();
}

}

这将给出以下输出:

名单:[达西,哥顿,梅耶,纽根,波波维奇,撒迦利亚]

搜索链接列表需要O(n)。 但是,由于对数据进行了排序,因此将下一个字符串放在适当位置只是找到正确位置的问题。 在由数组支持的另一个数据结构中,这是通过二进制搜索完成的,并采用O(log n)。 请参阅注释中的lreeder链接。 当然,您总是可以自己浏览列表并插入字符串,但这并不是链接列表最擅长的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM