0

I'm wondering if this is possible in Java. I want to insert it into the correct spot alphabetically. For example is the the LinkedList's (let's say it's called coollist) elements were : [Dusty, Gordon, Mayer, Popovic, Zechariah] and I try to insert another String by doing:

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

What can I do to make d the value that will insert it in alphabetical order, regardless of what's in the LinkedList? Can you guys help me out? I hope this makes sense.

Benny Hill
  • 6,191
  • 4
  • 39
  • 59
Delta Acf
  • 3
  • 1
  • 2
  • 2
    LinkedList won't do this, but PriorityQueue will. See http://stackoverflow.com/questions/416266/sorted-collection-in-java – lreeder Oct 09 '13 at 03:52

3 Answers3

2

Following is one way to find the sorted index in 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();
}

}

This will give the following output:

List: [Dusty, Gordon, Mayer, Nyugen, Popovic, Zechariah]

1

You can iterate though the list, searching for when the index produces a string that is greater than the argument. Then just insert behind that index. If this is a one-way linked list, you'll have to keep track of the previous node so you can update its fields.

    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
      }
    }
Mark
  • 31
  • 3
0

Searching a linked list takes O(n). But since your data is sorted, putting the next string in place is a matter of finding the right location. In another data structure backed by an array, this is done by binary search and takes O(log n). See lreeder's link in the comments. Of course you can always look through the list yourself and insert the string, but that's not what a linked list is best at.

clwhisk
  • 1,805
  • 1
  • 18
  • 17