Linked List and String Resources

Linked Lists can be very slow when removing dynamic Strings.
If you add and remove Strings in the
following way, the performance is very poor:
int n = 10000;
long time = System.currentTimeMillis ();
List list = new LinkedList();
for (int i = 0 ; i < n ; i++)
list.add ("" + n);
for (int i = n-1 ; i >= 0 ; i--)
list.remove(i/2);
- If you add and remove the not dynamic String: "" + 10000 instead,
- or do not remove the String (but add it in the middle),
- or use a ArrayList
the performance is much better.
I suppose it depends on handling the String resources.
If you run the following class, you will see what I mean:
public class SlowLinkedList
public static void main (String[] args)
// Be carefull when accessing/removing Strings in a Linked List.
testLinkedList ();
testLinkedListHardCodedString();
testLinkedListNoRemove();
testArrayList();
testArrayListNoParam();
private static void testLinkedList ()
int n = 10000;
long time = System.currentTimeMillis ();
List list = new LinkedList();
for (int i = 0 ; i < n ; i++)
list.add ("" + n);
for (int i = n-1 ; i >= 0 ; i--)
list.remove(i/2);
time = System.currentTimeMillis () - time;
System.out.println ("time dynamic String remove " + time);
private static void testLinkedListHardCodedString ()
int n = 10000;
long time = System.currentTimeMillis ();
List list = new LinkedList();
for (int i = 0 ; i < n ; i++)
list.add ("" + 10000);
for (int i = n-1 ; i >= 0 ; i--)
list.remove(i/2);
time = System.currentTimeMillis () - time;
System.out.println ("time same String remove " + time);
private static void testLinkedListNoRemove ()
int n = 10000;
long time = System.currentTimeMillis ();
List list = new LinkedList();
for (int i = 0 ; i < n ; i++)
list.add (i/2, "" + n);
time = System.currentTimeMillis () - time;
System.out.println ("time add dynamic String " + time);
private static void testArrayList ()
int n = 10000;
long time = System.currentTimeMillis ();
List list = new ArrayList();
for (int i = 0 ; i < n ; i++)
list.add ("" + n);
for (int i = n-1 ; i >= 0 ; i--)
list.remove(i/2);
time = System.currentTimeMillis () - time;
System.out.println ("time ArrayList " + time);
private static void testArrayListNoParam ()
int n = 10000;
long time = System.currentTimeMillis ();
List list = new ArrayList ();
for (int i = 0 ; i < n ; i++)
list.add ("" + 10000);
for (int i = n-1 ; i >= 0 ; i--)
list.remove(i/2);
time = System.currentTimeMillis () - time;
System.out.println ("time ArrayList same String " + time);
A typic output of the Performance is:
time dynamic String remove 1938
time same String remove 312
time add dynamic String 31
time ArrayList 63
time ArrayList same String 31

begin long winded reply
It doesn't matter if they are Strings or any other Object. LinkedList, in the way you are executing
remove, is not effecient. The LinkList remove will look at the index, if it is less than the median
it will start iterating from 0, if it is greater, it will start iterating in reverse from the end. Since you
are removing from the median, it will always take the longest (either forward or backward) to
get to the middle. Whereas, ArrayList simply uses the arraycopy to drop the element from the
array. The "NoRemove" test doesn't make sense to me in relation to the others.
Also, the VM is performing optimizations when you hardcode the 'n' value to 10000, it seems
that the VM won't optimize when using 'n'. Tusing Integer.toString(n), instead of "" + n,
in the first test case, it will yield better results.
My profs in college drove collections into my head and removing from a linked list without
an iterator is going to be inefficient. Iterators are a beautiful thing, use them.
Try this code instead, it simulates your remove in the middle with an iterator and, on my
machine, is faster than the ArrayList.
private static void testLinkedList() {
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++) {
        list.add (Integer.toString(n));
    boolean forward = false;
    for (ListIterator li = list.listIterator(n >> 1); li.hasNext() || li.hasPrevious();) {
        if (forward) {
            li.next();
            forward = false;
        } else {
            li.previous();
            forward = true;
        li.remove();
    time = System.currentTimeMillis () - time;
    System.out.println ("time dynamic String remove " + time);
}One other thing, run the tests more than once in a single VM and take the average. You could
apply some statistical analysis to figure out which is better within a certain confidence percentage,
but that is probably overkill. :)
Check the collection tutorial for more info: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html
end long winded reply
Matt

Similar Messages

  • Linked list to string coercion doesn't use text item delimiters: bug?

    set AppleScript's text item delimiters to {"; "} -- well-known technique
    {1, -1, "c", "d"} as string -- curly braces specify a vector, delimiters work
    -- result: "1; -1; c; d"
    {1, -1, "c", "d"} as linked list as string -- if coerced to linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as string -- square brackets specify a linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as vector as string -- coercing linked list to vector first works
    -- result: "1; -1; c; d"

    Hello
    It appears that linked list to string coercion does not respect the AppleScript's text item delimiters which are set to list of Unicode text. (Unicode TIDs have no effects in coercion as if it were set to {""})
    I can confirm this behaviour in both AppleScript 1.8.3 (OS9) and 1.9.1 (OSX10.2.8) at hand.
    So it has been as such for a long time. Bug I'd call it.
    By the way, although this is not the point, linked list is a historical residue and of little use in real scripting. After all, it is much slower than vector with appropriate coding. So we may always coerce it to vector without losing anything.
    Regards,
    H
    Linked list to string coercion & AppleScript's text item delimiters (TIDs).
    When AppleScript's TIDs are set to list of Unicode text,
    the TIDs have no effect in coercion from linked list to string as if they were set to {""}.
    set aa to [1, 2, "a", "b"]
    --set aa to {1, 2, "a", "b"} as linked list
    set t1 to list2text(aa, ";") -- "1;2;a;b" -- in pre-AppleScript 2.0
    set t2 to list2text(aa, ";" as Unicode text) --"12ab"
    return {t1, t2}
    on list2text(aa, delim)
    list aa : source list
    string delim : a text item delimiter
    return string
    local astid, astid0, t
    set astid to a reference to AppleScript's text item delimiters
    set astid0 to astid's contents
    try
    set astid's contents to {delim}
    --set t to aa as string
    --set t to aa as Unicode text
    set t to "" & aa
    set astid's contents to astid0
    on error errs number errn
    set astid's contents to astid0
    error errs number errn
    end try
    return t
    end list2text

  • Help with linked lists and searching

    Hi guys I'm very new to java. I'm having a problem with linked lists. the program's driver needs to create game objects, store them, be able to search the linked list etc. etc. I've read the API but I am really having trouble understanding it.
    First problem is that when I make a new game object through the menu when running the program, and then print the entire schedule all the objects print out the same as the latest game object created
    Second problem is searching it. I just really have no idea.
    Here is the driver:
    import java.util.*;
    public class teamSchedule
         public static void main (String[]args)
              //variables
              boolean start;
              game game1;
              int selector;
              Scanner scanner1;
              String date = new String();
              String venue = new String();
              String time = new String();
              String dateSearch = new String();
              double price;
              String opponent = new String();
              int addindex;
              List teamSchedLL = new LinkedList();
              String dateIndex = new String();
              String removeYN = new String();
              String venueIndex = new String();
              String opponentIndex = new String();
              start = true; //start makes the menu run in a while loop.
              while (start == true)
                   System.out.println("Welcome to the Team Scheduling Program.");
                   System.out.println("To add a game to the schedule enter 1");
                   System.out.println("To search for a game by date enter 2");
                   System.out.println("To search for a game by venue enter 3");
                   System.out.println("To search for a game by opponent enter 4");
                   System.out.println("To display all tour information enter 5");
                   System.out.println("");
                   System.out.println("To remove a game from the schedule enter search for the game, then"
                                            + " remove it.");
                   System.out.println("");
                   System.out.println("Enter choice now:");
                   scanner1 = new Scanner (System.in);
                   selector = scanner1.nextInt();
                   System.out.println("");
                   if (selector == 1)
                        //add a game
                        scanner1.nextLine();
                        System.out.println("Adding a game...");
                        System.out.println("Enter game date:");
                        date = scanner1.nextLine();
                        System.out.println("Enter game venue:");
                        venue = scanner1.nextLine();
                        System.out.println("Enter game time:");
                        time = scanner1.nextLine();
                        System.out.println("Enter ticket price:");
                        price = scanner1.nextDouble();
                        scanner1.nextLine();
                        System.out.println("Enter opponent:");
                        opponent = scanner1.nextLine();
                        game1 = new game(date, venue, time, price, opponent);
                        teamSchedLL.add(game1);
                        System.out.println(teamSchedLL);
                        System.out.println("Game created, returning to main menu. \n");
                        start = true;
                   else if (selector == 2)
                        //search using date
                        scanner1.nextLine();
                        System.out.println("Enter the date to search for in the format that it was entered:");
                        dateIndex = scanner1.nextLine();
                        if (teamSchedLL.indexOf(dateIndex) == -1)
                             System.out.println("No matching date found.  Returning to main menu.");
                             start = true;
                        else
                             //give user option to remove game if they wish.
                             System.out.println(teamSchedLL.get(teamSchedLL.indexOf(dateIndex)));
                             System.out.println("Would you like to remove this game? Y/N");
                             removeYN = scanner1.nextLine();
                             if (removeYN == "Y" || removeYN == "y")
                                  teamSchedLL.remove(teamSchedLL.indexOf(dateIndex));
                                  System.out.println("Scheduled game removed.");
                        System.out.println("\n Returning to main menu. \n");
                        start = true;
                   else if (selector == 3)
                        //search using venue name
                        scanner1.nextLine();
                        System.out.println("Enter the venue to search for in the format that it was entered:");
                        venueIndex = scanner1.nextLine();
                        if (teamSchedLL.indexOf(venueIndex) == -1)
                             System.out.println("No matching venue found.  Returning to main menu.");
                             start = true;
                        else
                             //give user option to remove game
                             System.out.println(teamSchedLL.get(teamSchedLL.indexOf(venueIndex)));
                             System.out.println("Would you like to remove this game? Y/N");
                             removeYN = scanner1.nextLine();
                             if (removeYN == "Y" || removeYN == "y")
                                  teamSchedLL.remove(teamSchedLL.indexOf(venueIndex));
                                  System.out.println("Scheduled game removed.");
                        System.out.println("\n Returning to main menu. \n");
                        start = true;
                   else if (selector == 4)
                        //search using opponent name
                        scanner1.nextLine();
                        System.out.println("Enter the opponent to search for in the format that it was entered:");
                        opponentIndex = scanner1.nextLine();
                        if (teamSchedLL.indexOf(opponentIndex) == -1)
                             System.out.println("No matching opponent found.  Returning to main menu.");
                             start = true;
                        else
                             //give user option to remove game
                             System.out.println(teamSchedLL.get(teamSchedLL.indexOf(opponentIndex)));
                             System.out.println("Would you like to remove this game? Y/N");
                             removeYN = scanner1.nextLine();
                             if (removeYN == "Y" || removeYN == "y")
                                  teamSchedLL.remove(teamSchedLL.indexOf(opponentIndex));
                                  System.out.println("Scheduled game removed.");
                        System.out.println("\n Returning to main menu. \n");
                        start = true;
                   else if (selector == 5)
                        //display tour info
                        System.out.println("Tour Schedule:");
                        System.out.println(teamSchedLL + "\n");
                   else
                        System.out.println("Incorrect choice entered. Returning to menu");
                        System.out.println("");
                        System.out.println("");
                        System.out.println("");
    and here is the game class:
    public class game
         private static String gameDate;
         private static String gameVenue;
         private static String gameTime;
         private static double gamePrice;
         private static String gameOpponent;
         public static String gameString;
         //set local variables equal to parameters
         public game(String date, String venue, String time, double price, String opponent)
              gameDate = date;
              gameVenue = venue;
              gameTime = time;
              gamePrice = price;
              gameOpponent = opponent;
         //prints out info about the particular game
         public String toString()
              gameString = "\n --------------------------------------------------------";
              gameString += "\n Date: " + gameDate + " | ";
              gameString += "Venue: " + gameVenue + " | ";
              gameString += "Time: " + gameTime + " | ";
              gameString += "Price: " + gamePrice + " | ";
              gameString += "Opponent: " + gameOpponent + "\n";
              gameString += " --------------------------------------------------------";
              return gameString;
    }I'm sure the formatting/style and stuff is horrible but if I could just get it to work that would be amazing. Thanks in advance.
    Message was edited by:
    wdewind

    I don't understand your first problem.
    Your second problem:
    for (Iterator it=teamSchedLL.iterator(); it.hasNext(); ) {
    game game = (game)it.next();
    // do the comparation here, if this is the game want to be searched, then break;
    }

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • Linear linked list and NullPointerException

    its a cd archive.
    the CDnode
    public class CDnode {
        public CD data;
        public CDnode neste;
    }The LinkedList class
    public class LinkedList {
        int length;   
        public CDnode firstNode;
        /** Creates a new instance of nesteedList */
        public LinkedList() {
            firstNode = new CDnode();
            length = 0;
        public int size(){
            return length;
        public void insertNewLastNode(CD data){
            CDnode N = new CDnode();
            N.data = data;
            N.neste = null;
            if(firstNode==null){
                firstNode = N;
            }else{
                CDnode P = firstNode;
                while(P.neste != null){
                    P = P.neste;
                P.neste = N;
            length++;
    }The cdarchive class
    import java.io.*;
    import java.util.*;
    * CDlengde.java
    * Created on 24. januar 2003, 17:54
    * @author  Standard
    public class CDArkiv2{
        //Klassevariablar
        LinkedList L = new LinkedList();
        static int lengde = 0;
        private CDnode forste;
        private final static char FELT_SLUTT_TEGN = '#';
        public CDArkiv2(){
        public void lesCdArkiv(String fil){
            lengde = 0;
            try{
                FileInputStream innFil = new FileInputStream(fil);
                DataInputStream innStrom = new DataInputStream(innFil);
                int anCD = innStrom.readInt();           
                for(int i = 1; i <= (anCD); i++){
                    CD nyCD = new CD();               
                    nyCD.lesCDData(innStrom);
                    leggTilCD(nyCD);
                innStrom.close();
            catch(IOException unntak){
                System.out.println("Feil ved unntak: " + unntak);           
        public void leggTilCD(CD ny){                     
            L.insertNewLastNode(ny);
            lengde++;       
        public void lagreCDArkiv(String fil){
            try{
                FileOutputStream utFilStrom = new FileOutputStream(fil, false);
                DataOutputStream utStrom = new DataOutputStream(utFilStrom);
                utStrom.writeInt(lengde);           
                for(int i = 0; i <= lengde; i++){
                    forste.data.skrivCDData(utStrom);
                utStrom.close();
            }catch(IOException unntak){
                System.out.println("Feil ved Unntak: " + unntak);
            }catch(NullPointerException u){
                System.out.println("Feil ved unntak: " + u);
        public void leggInnCD(){
            CD r = new CD();
            r.lesCD();       
            leggTilCD(r);
        public void slettCD(CD fjern){
        public void sokTittel(String sok){
            StringBuffer delstreng = new StringBuffer();
            StringBuffer temp = new StringBuffer();
            delstreng.append(sok);
            int w = 0;
            System.out.println("Du s�ker etter strengen " + sok + " i Cd titlane.");
            for(int i = 0; i <= lengde; i++){
                temp.append(forste.data.sTittel);
                boolean fins = sjekkStreng(delstreng, temp);
                if(fins == true){
                   forste.data.visCD();
                    w = 1;
                temp = new StringBuffer("");           
            if(w == 0){
                System.out.println("Det finst ingen cdar med den strengen.");
        public boolean sjekkStreng(StringBuffer sok, StringBuffer tittel){       
            int a = 0;
            boolean ermed = false;
            int lengd = tittel.length();
            int soklengd = sok.length();
            for (int i = 0;i < lengd; i++){
                if(tittel.charAt(i) == sok.charAt(a)){
                    a++;
                    if(soklengd == a){
                        ermed = true;
                        i = lengd;
            return ermed;
        public void skrivUtArtist(String artist){
            while(!(forste.neste == null)){           
                boolean erlik = artist.equals(forste.data.sArtist);           
                if(erlik == true){
                   forste.data.visCD();
                forste = forste.neste;
        public void skrivStat(List sj){
            int[] temp = new int[20];       
            System.out.println("\nDet er " + L.size() + " cdar i lengdeet\n\nFordelt i sjangrar:\n");
            while(L.firstNode.neste != null){           
                int e = L.firstNode.data.iSjanger;
                temp[e] += 1;
                L.firstNode = L.firstNode.neste;
            for(int i = 0; i <= 11; i++){
                if(temp[0] == 0){
                }else{
                System.out.print(temp);
    System.out.print(" " + sj.get(i) + " \n");
    When I try to access data in the cd list I get an nullpointereception error, like assiging int e = L.firstNode.data.iSjanger; Or when I try to save the list, I get a nullpointerexception, I seem to be able to create cd in the list but when I try to access the data its not there.

    It is an assignment I cant use the premade LinkedList package.
    While that did solve it, I can now add CDs to my archive but as I have found out when i try using other methods(like write to disk lagreCdArkiv() ) I get and nullpointerexception. I tried letting it rest and try another part of my assignment which included another linekd list. Same problem I can create a Hobby in a Hobbylist but when I try to compare and work with the data I get nullpointerexception.
    I must be doing something consistently wrong.
    Let me supply some more classes for comparison.
    public class Hobby {
        /** Namn p� hobbyen
        public String hobbyNamn;
        /** Noden i hobby
        public Hobby nesteHobby;
        /** Lager en ny hobby
         * @param hobby Namn p� hobbyen
        public Hobby(String hobby) {
            hobbyNamn = hobby;
            nesteHobby = null;
        /** lagar ein ny instans av hobby
        public Hobby(){
            hobbyNamn = "";
            nesteHobby = null;
    * nesteHobbyedList.java
    * Created on 5. februar 2003, 01:15
    /** klassen Hobbylist som inneheld metodar for manipulering av kjeda liste
    * @author Pote
    public class HobbyList {
        /** lengda p� lista
        int length;   
        /** den f�rste noden i lista
        Hobby firstNode;
        /** Konstrukt�r
        public HobbyList() {
            firstNode = null;
            length = 0;
        /** returnerer st�rrelsen til lista
         * @return returnener st�rrelsen
        public int size(){
            return length;
        /** Setter inn node sist i lista
         * @param data hobby objekt
        public void insertNewLastNode(Hobby data){
            Hobby N = new Hobby();
            N = data;
            N.nesteHobby = null;
            if(firstNode==null){
                firstNode = N;
            }else{
                Hobby P = firstNode;
                while(P.nesteHobby != null){
                    P = P.nesteHobby;
                P.nesteHobby = N;
            length++;
        /** set inn ein node alfabetisk
         * @param data hobby objekt
        public void insertAlfa(String namn){//insert  a hobby into the alfabetically
            if(firstNode != null){
            Hobby N = new Hobby(namn);
            N.nesteHobby = null;
            Hobby A = new Hobby();
            A = firstNode;
            Hobby G = new Hobby();
            G = firstNode;
            int o = 0;       
            while(A.nesteHobby != null){
            int i = N.hobbyNamn.compareTo(A.hobbyNamn);//compare the two hobby names
            if(o == 0){
            }else{
                G = G.nesteHobby;
            if(i < 0){
                if(o == 0){//if i < 0 N name coems ebfore A.name  and I insert N before A  G is my way of keeping track of the node before A and then inserting N between
                    N.nesteHobby = firstNode;
                }else{
                    G.nesteHobby = N;
                    N.nesteHobby = A;
                return;
            if(i == 0){
                System.out.println(N.hobbyNamn + " er registrert.");
                return;
            if(i < 0){           
                N.nesteHobby = A.nesteHobby;
                A.nesteHobby = N;
            A = A.nesteHobby;
            o = 1;
            length++;
        }else{
            Hobby N = new Hobby(namn);//if hobbylist is empty, make new hobby with parameter namn and set first
            firstNode = N;
    * Medlem.java
    * Created on 5. februar 2003, 21:34
    /** Klasse medlem som inneheld data om ein medlem.
    * Namn p� medlem, ei kjeda sortert liste, antal hobbyar som
    * vedkommande har og eit indeks nr som angir plass til eit
    * anna medlem med same interesser.
    * @author Pote
    public class Medlem {
        /** Namn p� medlem
        private String namn;
        /** int som held oversikt kor mange hobbyar medlemmet har, gjer samanlikining enklare
        public int antalHobbyar;
        /** angir indeks nr til medlem med like hobbyar ellers -1
        private int statusIndeks;
        /** Lagar ein Hobby node
        public Hobby hobbyListe;
        /** Lagar ei hobbyliste som inneheld metodar for liste manipulering
        HobbyList L = new HobbyList();
        /**Nr til medlemmet i datakontakt arrayen
        private int nr;
        /** Lager ein ny medlem med argumentet namn som er String
         * @param na Namn p� medlemmet
        public Medlem(String na) {
            namn = na;       
         /** Sett inn eit hobbynamn i lista til medlemmet i alfabetisk rekkef�lge
          * @param hobby Namn p� hobbyen
        public void insettHobbynamn(String hobby){       
            L.insertAlfa(hobby);
            antalHobbyar++;
        /** Sjekker om 2 medlemmer har same interesser
         * @param medlem2 Det medlemmet me skal sjekka mot
         * @return returnerer indeks nummeret p� medlemmet som passsar ellers
         * s� returneres -1
       public int passer2Sammen(Medlem medlem2){
            boolean lik = false;
            if(antalHobbyar == medlem2.antalHobbyar){//check if the number of hobbies match in case not terminate
                while(hobbyListe.nesteHobby != null){
                   if(L.firstNode.hobbyNamn == medlem2.hobbyListe.hobbyNamn){
                       hobbyListe.nesteHobby = medlem2.hobbyListe.nesteHobby;//if the hobbyname match lik(similar) is set to true for now
                       lik = true;
                   }else{
                       lik = false;//If it dont match  thne lik = false
                if(lik == false){
                    return -1;
                }else{
                    statusIndeks = medlem2.nr;//a way of making the 2 mebers referign to each other will be used in another class
                    medlem2.statusIndeks = nr;
                    return medlem2.statusIndeks;
            }else{
                return -1;
    import java.util.*;
    * Test.java
    * Created on 9. februar 2003, 18:02
    * @author  Standard
    public class Test {
        /** Creates a new instance of Test */
        public Test() {
         * @param args the command line arguments
        public static void main(String[] args) {
            Medlem a = new Medlem("K�re");
            Medlem b = new Medlem("Kari");
            a.insettHobbynamn("Aking");
            a.insettHobbynamn("AAking");
            b.insettHobbynamn("Aking");
            b.insettHobbynamn("AAking");
            int i = b.passer2Sammen(a);
            System.out.println(i);
    }

  • Linked Lists, Hashing, and sore heads.

    I am working with a team on a java program as part of an algorithms assignment. We have completed the program however I'm convinced its not working. The program is supposed to carry out a defined number of searches, additionions and deletions to a linked list and time it. We have been supplied with a number of ext files with random numbers for testing purposes.
    The text files are different sizes. We are finding that our results are the same regardless which file we use and which arguments are passed into the program. I would be greatful if someone could cast their eye over the work and let us know what you think.
    All files are at
    http://students.odl.qmul.ac.uk/~dm07/algorithms/.
    IntSet.java is the program we have completed from a skeleton code.
    Evaluator.java is the wrapper provided. data.zip is a full file of the
    different test text files although there are two on here for quick download.
    Any direction or feedback would be really appreciated.
    Dermot.

    Here is the result for the 50 random numbers text file :
    D:\Coursework\Algorithms>java Evaluator size-50-random.txt 10000
    Setting up, please wait ...
    Finished setting up.
    Start searches
    It took 0.010 seconds for 10000 searches
    It took 0.020 seconds for 10000 additions
    It took 0.010 seconds for 10000 deletions
    And here is the result for hte 50000 random numbers text file :
    D:\Coursework\Algorithms>java Evaluator size-50000-random.txt 10000
    Setting up, please wait ...
    Finished setting up.
    Start searches
    It took 0.010 seconds for 10000 searches
    It took 0.020 seconds for 10000 additions
    It took 0.000 seconds for 10000 deletions
    As you can see they are virtually identical. Even after running a number of times and working out averages they are the same. I thought that the results should be exponential but they are not. I understand that results should change from pc setup to pc setup, depending on processor etc but we are not getting this.
    Dermot.

  • Alphabetizing a linked list, HELP!

    To all:
    Firstly, I'm not looking for someone to do my assignment for me. I just need a push in the right direction...
    I need to create a linked list that contains nodes of a single string (a first name), but that list needs to be alphabetized and that's where I am stuck.
    I can use an iterator method that will display a plain-old "make a new node the head" linked list with no problem. But I'm under the impression that an iterator method is also the way to go in alphabetizing this list (that is using an iterative method to determine the correct place to place a new node in the linked list). And I am having zero luck doing that.
    The iterator method looks something like this:
    // ---- MyList: DisplayList method ----
    void DisplayList()
    ListNode p;
    for (ResetIterator(); (p = Iterate()) != null; )
    p.DisplayNode();
    // ---- MyList: ResetIterator method ----
    void ResetIterator()
    current = head;
    // ---- MyList: Iterate method ----
    ListNode Iterate()
    if (current != null)
    current = current.next;
    return current;
    Can I use the same iterator method to both display the final linked list AND alphabetize my linked list or do I need to create a whole new iterator method, one for each?
    Please, someone give me a hint where to go with this. I've spent something like 15 hours so far trying to figure this thing out and I'm just stuck.
    Thanks so much,
    John
    [email protected]

    I'll try and point you in the right direction without being too explicit as you request.
    Is your "linked list" an instance of the Java class java.util.LinkedList or a class of your own?
    If it is the Java class, then check out some of the other types of Collections that provide built-in sorting. You should be able to easily convert from your List to another type of Collection and back again to implement the sorting. (hint: you can do this in two lines of code).
    If this is your own class and you want to code the sort yourself, implement something simple such as a bubble sort (should be easy to research on the web).
    Converting to an array, sorting that and converting back is another option.
    Good Luck.

  • Same things in a linked list

    i have a linked list and i am adding to it all the time. The list holds objects that contain a string and a int. When i add an object i want to check to see if an object already exists with the same value in the string. If there is i increment the int and dont add the new object. Does anyone have any helpful code or suggestions????

    You could either use List.contains, or you could just use a Set instead of a List. (See the API docs for both to determine which is more suited to your needs.)
    Either way, you'll have to override equals() and hashCode() on your object.
    See this chapter in Josh Bloch's book for some good tips on what to put into those methods

  • How  to Implement a Chained Hash Table with Linked Lists

    I'm making a migration from C/C++ to Java, and my task is to implement a Chained Hash Table with a Linked List. My problem is to put the strings(in this case names) hashed by the table using de Division Metod (H(k)= k mod N) in to a Linked list that is handling the colisions. My table has an interface implemented(public boolean insert(), public boolean findItem(), public void remove()). Any Help is needed. Thanks for everyone in advance.

    OK. you have your hash table. What you want it to do is keep key/value pairs in linked lists, so that when there is a collision, you add the key/value pair to the linked list rather than searching for free space on the table.
    This means that whenever you add an item, you hash it out, check to see if there is already a linked list and if not, create one and put it in that slot. Then in either case you add the key/value pair to the linked list if the key is not already on the linked list. If it is there you have to decide whether your requirements are to give an error or allow duplicate keys or just keep or modify one or the other (old/new).
    When you are searching for a key, you hash it out once again and check to see if there is a linked list at that slot. If there is one, look for the key and if it's there, return it and if not, or if there was no linked list at that slot, return an error.
    You aren't clear on whether you can simply use the provided linked-list implementations in the Java Collections or whether you have to cobble the linked list yourself. In any case, it's up to you.
    Is this what you're asking?
    Doug

  • Circular linked list while loop

    i have a circular linked list and i'd like a while loop to iterate though all of them. my problem is that it always excludes the last node. i know why, it's due to the fact that "current.next != alive" skips it from ever accessing the last node. i can't seem to solve it. note that the last node in the list points to the first node (alive):
                   while(current.next != alive )
                        prev = prev == null ? prev = alive : prev;
                        //identify the name with it's matching node
                        if(name.equals(current.name.toLowerCase()))
                             prev.next = current.next;
                             dead = current;
                             current = current.next;
                             dead.next = null;
                             while(dead.next != null)
                                  dead = dead.next;
                        else
                             prev = current;
                             current = current.next;     
                   }

    //this class assists the client in managing a game of assassinations. it does so by providing options such as verifying a target's existence, getting the list of dead people, getting the lsit of alive people, and moving people from the alive to dead list
    public class AssassinManager
         private AssassinNode alive;
         private AssassinNode alive_tail;
         private AssassinNode dead;
         //pre: must send a string array
         //post: nodes are created
         public AssassinManager(String[] names)
              dead = null;
              alive = new AssassinNode(names[0]);
              AssassinNode current = alive;
              System.out.println(names[0] + " is first, " + names[(names.length-1)] + " is last\n\n");
              for(int i = 1; i < names.length; i++)
                   while(current.next != null)
                        current = current.next;
                   current.next = new AssassinNode(names);
              alive_tail = current.next = new AssassinNode(names[(names.length - 1)], alive);
         //post: outputs all the people still alive
         public void printKillRing()
              AssassinNode last = null, current = alive;
              while(current.next!= alive)
                   System.out.println(current.name + " is stalking " + current.next.name);
                   last = current.next;
                   current = current.next;
              System.out.println(current.name + " is stalking " + alive.name);
         //post: outputs a list of the dead people
         public void printGraveyard()
              AssassinNode last = null, current = dead;
              while(dead != null)
                   System.out.println(current.name + " was killed by " + current.killer);
                   last = current.next;
                   current = current.next;
         //pre: must send a string name
         //post: will return true/false depending on the input if the name is in the killing ring (alive)
         public boolean killRingContains(String name)
              AssassinNode current = alive;
              name = name.toLowerCase();
              while(current.next!= alive)
                   if(name.equals(current.name.toLowerCase()))
                        return true;
                   current = current.next;
              return false;
         //pre; must send a string name
         //post: will return true/false if the name is in the graveyard list
         public boolean graveyardContains(String name)
              AssassinNode current = dead;
              name = name.toLowerCase();
              while(dead != null && current.next != null)
                   if(name.equals(current.name.toLowerCase()))
                        return true;
                   current = current.next;
              return false;
         //post: checks if game is over by seeing if there is more than 1 player
         public boolean gameOver()
              AssassinNode current = alive;
              if(current.next == null)
                   return true;
              return false;
         //post: outputs the winner's name
         public String winner()
              AssassinNode current = alive;
              if(current.next == null)
                   return alive.name;
              return null;
         //pre: must send a string name that exists is alive
         //post: will remove the user from the alive list and add it to the killed list
         public void kill(String name)
              //check if person exists to remove them from alive list
              if(killRingContains(name.trim()) == true)
                   AssassinNode prev = null, current = alive, dead = this.dead;
                   name = name.toLowerCase();
                   while(current != null)
                        System.out.println(current.name);
                        if(name.equals(current.name.toLowerCase()))
                             prev = prev == null ? alive_tail : prev;
                             prev.next = current.next;
                             //dead = dead == null ? current : dead;
                             //while(dead.next != null)
                                  //dead = dead.next;
                             if(prev.next == alive)
                                  break;
                             current = prev.next;
                        else
                             if(current.next == alive)
                                  break;
                             prev = current;
                             current = current.next;
    }Edited by: ixxalnxxi on Apr 27, 2008 12:58 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Linked lists problem -- help needed

    Hello again. I've got yet another problem in my C++ course that stems from my use of a Mac instead of Windows. I'm going to install Parallels so I can get Windows on my MacBook and install Visual Studio this week so that I don't have to deal with these discrepancies anymore, but in the meanwhile, I'm having a problem here that I don't know how to resolve. To be clear, I've spent a lot of time trying to work this out myself, so I'm not just throwing this up here to have you guys do the work for me -- I'm really stuck here, and am coming here as a last resort, so I'll be very, very appreciative for any help that anyone can offer.
    In my C++ course, we are on a chapter about linked lists, and the professor has given us a template to make the linked lists work. It comes in three files (a header, a source file, and a main source file). I've made some adjustments -- the original files the professor provided brought up 36 errors and a handful of warnings, but I altered the #include directives and got it down to 2 errors. The problematic part of the code (the part that contains the two errors) is in one of the function definitions, print_list(), in the source file. That function definition is shown below, and I've marked the two statements that have the errors using comments that say exactly what the errors say in my Xcode window under those two statements. If you want to see the entire template, I've pasted the full code from all three files at the bottom of this post, but for now, here is the function definition (in the source file) that contains the part of the code with the errors:
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    As you can see, the problem is with the two statements that contain the 'setw' function. Can anyone help me figure out how to get this template working and get by these two errors? I don't know enough about linked lists to know what I can and can't mess with here to get it working. The professor recommended that I try using 'printf' instead of 'cout' for those two statements, but I don't know how to achieve the same effect (how to do whatever 'setw' does) using 'printf'. Can anyone please help me get this template working? Thank you very, very much.
    For reference, here is the full code from all three files that make up the template:
    linkedlist.h (header file):
    #ifndef LINKED_LINKED_H
    #define LINKED_LINKED_H
    struct NODE
    string name;
    int test_grade;
    NODE * link;
    class Linked_List
    public:
    Linked_List();
    void insert(string n, int score);
    void remove(string target);
    void print_list();
    private:
    bool isEmpty();
    NODE *FRONT_ptr, *REAR_ptr, *CURSOR, *INSERT, *PREVIOUS_ptr;
    #endif
    linkedlist.cpp (source file):
    #include <iostream>
    using namespace std;
    #include "linkedlist.h"
    LinkedList::LinkedList()
    FRONT_ptr = NULL;
    REAR_ptr = NULL;
    PREVIOUS_ptr = NULL;
    CURSOR = NULL;
    void Linked_List::insert(string n, int score)
    INSERT = new NODE;
    if(isEmpty()) // first item in List
    // collect information into INSERT NODE
    INSERT-> name = n;
    // must use strcpy to assign strings
    INSERT -> test_grade = score;
    INSERT -> link = NULL;
    FRONT_ptr = INSERT;
    REAR_ptr = INSERT;
    else // else what?? When would this happen??
    // collect information into INSERT NODE
    INSERT-> name = n; // must use strcpy to assign strings
    INSERT -> test_grade = score;
    REAR_ptr -> link = INSERT;
    INSERT -> link = NULL;
    REAR_ptr = INSERT;
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    void Linked_List::remove(string target)
    // 3 possible places that NODES can be removed from in the Linked List
    // FRONT
    // MIDDLE
    // REAR
    // all 3 condition need to be covered and coded
    // use Trasversing to find TARGET
    PREVIOUS_ptr = NULL;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    if(CURSOR->name == target) // match
    { break; } // function will still continue, CURSOR will
    // mark NODE to be removed
    else
    { PREVIOUS_ptr = CURSOR; } // PREVIOUS marks what NODE CURSOR is marking
    // JUST before CURSOR is about to move to the next NODE
    if(CURSOR == NULL) // never found a match
    { return; }
    else
    // check each condition FRONT, REAR and MIDDLE
    if(CURSOR == FRONT_ptr)
    // TARGET node was the first in the list
    FRONT_ptr = FRONT_ptr -> link; // moves FRONT_ptr up one node
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    }// why no need for PREVIOUS??
    else if (CURSOR == REAR_ptr) // TARGET node was the last in the list
    { // will need PREVIOUS for this one
    PREVIOUS_ptr -> link = NULL; // since this node will become the last in the list
    REAR_ptr = PREVIOUS_ptr; // = REAR_ptr; // moves REAR_ptr into correct position in list
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    else // TARGET node was the middle of the list
    { // will need PREVIOUS also for this one
    PREVIOUS_ptr -> link = CURSOR-> link; // moves PREV nodes' link to point where CURSOR nodes' points
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    bool Linked_List::isEmpty()
    if ((FRONT_ptr == NULL) && (REAR_ptr == NULL))
    { return true; }
    else
    { return false;}
    llmain.cpp (main source file):
    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    #include "linkedlist.h"
    int main()
    Linked_List one;
    one.insert("Angela", 261);
    one.insert("Jack", 20);
    one.insert("Peter", 120);
    one.insert("Chris", 270);
    one.print_list();
    one.remove("Jack");
    one.print_list();
    one.remove("Angela");
    one.print_list();
    one.remove("Chris");
    one.print_list();
    return 0;

    setw is the equivalent of the field width value in printf. In your code, the printf version would look like:
    printf("%8s", CURSOR->name.c_str());
    I much prefer printf over any I/O formatting in C++. See the printf man page for more information. I recommend using Bwana: http://www.bruji.com/bwana/
    I do think it is a good idea to verify your code on the platform it will be tested against. That means Visual Studio. However, you don't want to use Visual Studio. As you have found out, it gets people into too many bad habits. Linux is much the same way. Both development platforms are designed to build anything, whether or not it is syntactically correct. Both GNU and Microsoft have a long history of changing the language standards just to suit themselves.
    I don't know what level you are in the class, but I have a few tips for you. I'll phrase them so that they answers are a good exercise for the student
    * Look into const-correctness.
    * You don't need to compare a bool to 1. You can just use bool. Plus, any integer or pointer type has an implicit cast to bool.
    * Don't reuse your CURSOR pointer as a temporary index. Create a new pointer inside the for loop.
    * In C++, a struct is the same thing as a class, with all of its members public by default. You can create constructors and member functions in a struct.
    * Optimize your function arguments. Pass by const reference instead of by copy. You will need to use pass by copy at a later date, but don't worry about that now.
    * Look into initializer lists.
    * In C++ NULL and 0 are always the same.
    * Return the result of an expression instead of true or false. Technically this isn't officially Return Value Optimization, but it is a good habit.
    Of course, get it running first, then make it fancy.

  • User to call the name on a linked list from the console

    Hello,
    My program has 9 linked lists and I need to manipulate them depending on which one the user wants to add or remove from. The problem is it's different every time. I need a way to allow the user to input the name of one of the linked lists, and then from there I can manipulate that list. My general idea is as follows though the syntax is wrong.
    inputFrom = in.nextLine();
    inputFrom = inputFrom.toUpperCase();
    if (inputFrom.peek() != null){
    System.out.println("This list has data);
    {code}
    My problem is that in that if statement I can not simply place the variable in front of the action I wish to perform and expext the variable to substitute for the actual list's name. How can I work around this? Thank you in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Create a Map<String, List>, where String is the name of the list. Then you can do map.get("listName");

  • Help on Linked List

    Hey people, i need a small help on my linked list.
    Ok, what i'm trying to do is have a search function with a linked list using strings. First i will have a string, i will then compute the ASCII value for that and take MOD 71 lets say. For example, a string has an ASCII value of 216, MOD 71 of this gives me 3. I will then have an array of 71, and each array will point to a linked list. There will be as many linked list as there are of arrays (71). I will then store this string at index [3] in the linked list in which the array points to.
    My problem for now is, how do i for example create 71 linked list? So far i can create only 1. To create another is easy, but if i have 71 the code will be too much. Is there an iterator i could use that easily creates 71? Sorry about this, i'm not really good with linked list with Java. Anyway, here is what i have now :).
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public static MyLinkedListElement head;
        public MyLinkedList() {   
            head = null;
       public static void addToHead(String s) {
            MyLinkedListElement a = new MyLinkedListElement(s);
            if (head == null) {
                head = a;
            } else {
                a.next = head;
                head = a;       
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              for (int i = 0; i < arr.length; i++) {
                          addToHead(arr);
    MyLinkedListElement current = head;
    while (current != null) {
    System.out.println(current.getValue());
    current = current.next;
    }I can have an array of strings and easily add them to a linked list.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I am very confused now, i just need to store a string value inside an array of linked list. But i can't somehow do it. I am very close, i can store the value in a linked list but the array of linked list, this is what i have.
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public MyLinkedListElement head;
        public MyLinkedList() {   
              head = null;
        public void addToHead(String s) {
             MyLinkedListElement  a = new MyLinkedListElement(s);
             MyLinkedList[] arrayOfLinkedLists = new MyLinkedList[71];
             for(int i = 0; i < arrayOfLinkedLists.length; i++) {
                 arrayOfLinkedLists[i] = new MyLinkedList();
             if (head == null) {    
                 head = a;
             } else {
                 a.next = head;
                 head = a;       
        public void print(MyLinkedListElement current) {
              while (current  != null) {
                    System.out.println(current.getValue());
                    current = current.next;
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              MyLinkedList listInstance = new MyLinkedList();
              for (int i = 0; i < arr.length; i++) {
                    listInstance.addToHead(arr);
    MyLinkedListElement current = listInstance.head;
    listInstance.print(current);

  • Array of Linked List Help

    I am fairly new to Java, and Linked Lists. Can you tell me how I can fix my code? Why does my code print infinite "3" s. That is all I am trying to do is create a linked list and put that linked list into index 2 of the array. In the loop, I am setting up a whole bunch on null Node's, is it even possible to link all these nodes together in that same loop? If something does not make sense, I will try to elaborate. I will eventually impliment an insert method in the Node class, are there any pointers on how to implement it? What are the special cases I need to be looking for when implementing the insert method?
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package testlinkedlist;
    * @author Ben
    public class Main {
         * @param args the command line arguments
        public static Node l;
        public static Node p = new Node();
        public static Node Front;
        public static void main(String[] args) {
            Node[] anArray = new Node[4];
            for(int i = 0; i < 4; i++){
                anArray[i] = new Node();
                l = new Node(i);
                l.setLink(l);
            anArray[2] = l;         
            while(anArray[2] != null){
                System.out.println(anArray[2].dataInNode());
                anArray[2] = anArray[2].next;
    }

    l = new Node(i);
    l.setLink(l);The node l is created in line one, in line two a link is created from l to l. In other words here is the presence of your infinite loop which is magnified in the following piece of code:
    anArray[2] = l;         
    while(anArray[2] != null){
      System.out.println(anArray[2].dataInNode());
      anArray[2] = anArray[2].next;
    }Mel

  • Link List Key

    Hello,
    In the IMG activity Define links on confirmation page, i can configure what links to display on the confirmation page of a ESS/MSS application and it works fine.
    The question i have is: Can i create a custom link list? If yes, how can i hook that up to a custom service/resource.
    I would prefer not to change the standard SAP entries of the link lists and therefore would want to know how does the link list concept work?
    Thanks,
    Bhushan.

    Never mind, i found an answer to my question on this site in a very good blog by Antony Raja T.
    For other users who might need it, here is the link:
    /people/antonyraja.t/blog/2007/12/16/confirmation-screen-links-in-self-service-applications
    Thanks,
    Bhushan.

Maybe you are looking for

  • Reporting Doubts

    Hi experts, How to replace a key date variable value with a selection option variable in the query runtime ? And also in the selection option variable is there any chance to fix the selection option to be <= ( Less than or equal to ). Regards, V N.

  • Unable to build valid certificate chain

    Hi, I am trying to sign my AIR application using the Code Signing Certificate I got from Apple (iPhone Dev). I have Apple's Root Certificate and my certificate. I installed both and then exported my certificate as pkcs12 (.p12 file) using many method

  • HT1430 how can i get my  ipad from being stuck on the icloud backup?

    My ipad is stuck on the iclouf backup. how can i fix this problem?

  • Adobe Reader Crashes Using Deigner 7 form

    Hello, I have a form I made in Designer 7 and when opened using Adobe Reader 7 it crashes. It crashes when I use the dropdown field that makes another field visible/invisible to be specific and it does it on every such field. Here is the code that is

  • Time Capsule still can't create backups

    I keep getting the message "Unable to complete backup. An error occurred while copying files to the backup volume" I have tried everything on the Forums, like; re-naming my TC, Giving my sharing folder a name, deleting the sparse bundle, deliting the