2013-10-09 19 views
0

我想知道这在Java中是否可行。我想按字母顺序将它插入正确的位置。 例如是LinkedList的的(比方说,这就是所谓的coollist)要素是:尘土飞扬,戈登,迈耶,波波维奇,撒迦利亚] ,我尝试做插入另一个字符串:按字母顺序将新对象插入到字符串(字符串)中,无需排序

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

我能做些什么使d按照字母顺序插入它的值,而不管LinkedList中有什么值?你们能帮我吗? 我希望这是有道理的。

+2

链表不会做这个,但是PriorityQueue会。请参阅http://stackoverflow.com/questions/416266/sorted-collection-in-java – lreeder

回答

1

以下是在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(); 
} 

}

这会给下面的输出:

列表:尘土飞扬,戈登,迈耶,Nyugen,波波维奇,撒迦利亚]

+0

这正是我想到的。它完美的作品。多谢兄弟。 –

0

搜索链接列表需要O(n)。但是由于你的数据是排序的,把下一个字符串放在适当的位置就是找到正确的位置。在由数组支持的另一个数据结构中,这是通过二进制搜索完成的,并采用O(log n)。请参阅评论中的货主链接。当然,你总是可以自己查看列表并插入字符串,但这不是链接列表最擅长的。

1

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

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 
     } 
    } 
相关问题