簡體   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