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);
}

Similar Messages

  • 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

  • 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.

  • 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;
    }

  • 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.

  • Circular Linked List Help

    Hi,
    I'm developing a circular linked list class.. However everytime I add to the front of the list it overwrites the first element in the list.. I pretty confused at the moment. If anyone could assist me in what I'm doing wrong it would be greatly appreciated..
    My Class:
    public class CNode<T>
         public T nodeValue;          //data held by the node
         public CNode<T> next;     //next node in the list
         //default constructor; next references node itself
         public CNode()
              nodeValue = null;
              next = this;
         //constructor; initializes nodeValue to item
         //and sets the next to reference the node itself
         public CNode(T item)
              nodeValue = item;
              next = this;
    }My addFirst:
    public static <T> void addFirst(CNode<T> header, T item)
              CNode<T> curr;
              CNode<T> newNode = new CNode<T>(item);
              //header.next = newNode;
              //newNode.next = header;
              curr = header;
              newNode.next = header;
              curr.next = newNode;
         }

    You need a Node class and a class that manages the nodes. The class the manages the nodes is typically called something like MyLinkedList. The MyLinkedList class will typically have a member called 'head' or 'first' and another member called 'last', 'end', or 'tail'. Those members will contain references to the first node and the last node respectively.
    The methods like add(), remove(), find(), etc. will be members of the MyLinkedList class--not the Node class. The add() method of the MyLinkedList class will create a node, set the value of the node, and then set the next member to refer to the proper node or null if the node is added to the end of the list. Therefore, there is really no need for a default constructor in the node class. The MyLinkedList class will always set the value of the node, and then set it's next member to refer to something.
    You might want to try to write a linear linked list first, and get that working, and then modify it to make it a circular linked list. In addition, you should be drawing pictures of nodes with arrows connecting the different nodes to understand what's going on. Whenver the next member of a node refers to another node, draw an arrow starting at the next member and ending at the node it refers to. The pictures will be especially helpful when you write functions like add().
    Message was edited by:
    7stud

  • Question about Linked Lists

    I'm doing an assignment on linked lists and I'm having trouble understanding the insert method. I'm using the one from the book and it works fine, but I don't quite understand it.
    public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
    head = n;
    else
    previous.next = n;
    current = n;
    It's my understanding that current is the value that your currently at in the list. Previous is equal to the value before the current. So, previous.next is equal to current. This reasoning won't make the list progress with this code. Can someone tell me what I'm not understanding, or explain how this progresses?

    Thanks, that helps alot. Now, I have another question. I need to add and remove nodes from the list. I have it setup where the user can choose what node to delete. It compiles and runs fine, but when I try to delete a node, it doesn't delete it. Doing some troubleshooting, I found that it gets into the for loop, but doesn't do anything with the if/else statement. I put a printline in the if and else part, and it never printed out the statement in the if statement or in the else statement. Here's the code I'm using. getLentgh() is a method I wrote to return an integer value of how many nodes are in the list. I've also tried putting in a printline after the for loop, but still in the try, it didn't print it out.
    else if(source == remove) {
    String del = JOptionPane.showInputDialog("Enter an integer to remove.");
    Node temp = new Node(del,current);
    if(del != null){
    try{
         for(int c = 0; c < list.getLength(); c++){            
         if(temp.data == current.data){
              list.remove();
              c = list.getLength();
         else{
              list.advance();     
    }catch(NullPointerException e){
    }

  • Using compareTo() in a Linked List Please Help!!

    I'm trying to compare strings in a Linked List and it throws a null pointer exception somewhere in the method smallest() which is where i have the strings(nodes) comparing each other. I've been Trying to find the answer for two days now and I've gotten nowhere. PLEASE HELP! The code is as follows:
    public String smallest()
      // Returns smallest String in StringLog in terms of lexicographic ordering.
       //Precondition: StringLog is not empty.
    LLStringNode node;
    LLStringNode node2;
    LLStringNode node3 = log;
    node = log;
    node2 = log;
    String smallString = "Bob";
    boolean notNull = (node != null);
    boolean notNull2 = (node2 != null);
    while (notNull && notNull2)
         System.out.println(node.getInfo() + " " + node2.getInfo());
         if (node.getInfo().compareTo(node2.getInfo()) <= 0)
           node3 = node;
           node2 = node2.getLink();
           smallString = node3.getInfo();
         else if (notNull && notNull2)
           node3 = node2;
          node =  node.getLink();
          smallString = node3.getInfo();
          smallString = node3.getInfo();
          return smallString;
    }I've inserted a line of code that shows the output of the method in the test driver before it throws the exception it is as follows: note I have already input strings through the test driver.
    Choose an operation:
    1: insert(String element)
    2: howMany(String element)
    3: clear()
    4: contains(String element)
    5; isFull()
    6; isEmpty()
    7: size()
    8: uniqInsert(String element)
    9: getName()
    10: toString()
    11: smallest()
    12: Stop testing
    11
    Exception in thread "main" lamb lamb
    lamb cat
    cat cat
    cat apple
    apple apple
    apple dog
    apple thing
    apple girl
    apple boy
    java.lang.NullPointerException
         at LinkedStringLog.smallest(LinkedStringLog.java:189)
         at CMPS39001.main(CMPS39001.java:121)Below is the full class of LinkedStringLog which contains the smallest() method(you may or may not need this i'm not sure)
    {codepublic class LinkedStringLog implements StringLogInterface
      protected LLStringNode log; // reference to first node of linked
                                  // list that holds the StringLog strings
      protected String name;      // name of this StringLog
      public LinkedStringLog(String name)
      // Instantiates and returns a reference to an empty StringLog object
      // with name "name".
        log = null;
        this.name = name;
    public void insert(String element)
    // Precondition: This StringLog is not full.
    // Places element into this StringLog.
    LLStringNode newNode = new LLStringNode(element);
    newNode.setLink(log);
    log = newNode;
    public int howMany(String element)
    // Returns an int value of how many times it occurs in StringLog
    int eleCount = 0;
         LLStringNode node;
         node = log;
         while (node != null)
         if (element.equalsIgnoreCase(node.getInfo()))
              eleCount ++;
              node = node.getLink();
              else
              node = node.getLink();
         return eleCount;
    public boolean isFull()
    // Returns true if this StringLog is full, false otherwise.
    return false;
    public boolean isEmpty()
    // Returns true if StringLog is empty, it otherwise returns false.
         boolean isNull = true;
         LLStringNode node;
         node = log;
         boolean searchEmpty = (node != null);
    if (searchEmpty)
         isNull = false;
         return isNull;
    return isNull;
    public boolean uniqInsert(String element)
    // Inserts element in stringLog unless an identical string already exists in the StringLog
    LLStringNode node;
         node = log;
         boolean found = false;
         boolean searchMore;
         searchMore = (node != null);
         while (searchMore && !found)
         if (element.equalsIgnoreCase(node.getInfo()))
              return found;
              else
              node = node.getLink();
              searchMore = (node != null);
         if (found = true)
              LLStringNode newNode = new LLStringNode(element);
              newNode.setLink(log);
              log = newNode;
         return found;
    public int size()
    // Returns the number of Strings in this StringLog.
    int count = 0;
    LLStringNode node;
    node = log;
    while (node != null)
    count++;
    node = node.getLink();
    return count;
    public boolean contains(String element)
    // Returns true if element is in this StringLog,
    // otherwise returns false.
    // Ignores case difference when doing string comparison.
    LLStringNode node;
    node = log;
    boolean found = false;
    boolean moreToSearch;
    moreToSearch = (node != null);
    while (moreToSearch && !found)
    if (element.equalsIgnoreCase(node.getInfo())) // if they match
    found = true;
    else
    node = node.getLink();
    moreToSearch = (node != null);
    return found;
    public void clear()
    // Makes this StringLog empty.
    log = null;
    public String getName()
    // Returns the name of this StringLog.
    return name;
    public String toString()
    // Returns a nicely formatted string representing this StringLog.
    String logString = "Log: " + name + "\n\n";
    LLStringNode node;
    node = log;
    int count = 0;
    while (node != null)
    count++;
    logString = logString + count + ". " + node.getInfo() + "\n";
    node = node.getLink();
    return logString;
    public String smallest()
    // Returns smallest String in StringLog in terms of lexicographic ordering.
    //Precondition: StringLog is not empty.
    LLStringNode node;
    LLStringNode node2;
    LLStringNode node3 = log;
    node = log;
    node2 = log;
    String smallString = "Bob";
    boolean notNull = (node != null);
    boolean notNull2 = (node2 != null);
    while (notNull && notNull2)
         System.out.println(node.getInfo() + " " + node2.getInfo());
         if (node.getInfo().compareTo(node2.getInfo()) <= 0)
         node3 = node;
         node2 = node2.getLink();
         smallString = node3.getInfo();
         else if (notNull && notNull2)
         node3 = node2;
    node = node.getLink();
    smallString = node3.getInfo();
         smallString = node3.getInfo();
    return smallString;

    line 189 is
    if (node.getInfo().compareTo(node2.getInfo()) <= 0)and the other line mentioned is just the call.
    But that line runs several times until a certain point and then throws the error. Example, in the test driver every time that line is ran it is outputting the nodes in the test driver that I posted.

  • Changing data in a linked list object.

    hi,
    i'm still pretty new to java, so bear with me if i am making stupid mistakes, heh.
    i'm having trouble with changing data in an object stored in a singly-linked list. i've created a class that will store polynomials in sorted order (descending) in a singly-linked list. each linked list is one polynomial, and each node references to a polynomial object that stores two ints: the coefficient and the exponent of that term.
    i'm having trouble when it comes to 'collecting like terms,' though. here's a rough skeleton of my code:
    public class Polynomial
    private LinkedList polynoList;
    private LinkedListItr Itr;
    private int coeff;
    private int exponent;
    public Polynomial()
    zeroPolynomial();
    } // this constructor sets up an empty linked list
    public Polynomial( int c, int e )
    coeff = c;
    exponent = e;
    } // this creates a Polynomial object storing the two ints
    public void zeroPolynomial()
    polynoList = new LinkedList();
    theItr = polynoList.zeroth();
    } // this method creates the empty linked list and sets the
    //iterator on the zeroth node.
    //various other methods are here, not relevant to my post
    //this next method is the one i am having trouble with.
    //it takes two ints as parameters, the coefficient
    //and the exponent.
    public void insertTerm( int c, int e )
    //...i have a few if/then statements here
    //so that the terms can be inserted in descending order.
    LinkedListItr tester = polynoList.first();
    //the 'tester' iterator is set on the first node
    //this following if statement retrieves the exponent
    //in the current node by casting the information
    //retrieved from the LinkedList retrieve() method
    //into Polynomial, then compares it to the current
    //exponent. if they are equal, i want to add the
    //coefficients.
    if( e == ((Polynomial)tester.retrieve()).getExp() )
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    //a main method goes here wherein the user can insert
    //terms, print the polynomial, etc.
    }//end Polynomial class
    can anyone help me out? the code i'm using compiles correctly, but it does not change the value of the current coeff variable as i'd like to think it should. any input would be GREATLY appreciated, thanks!

    hey,
    thanks for the reply...
    i am sure that ((Polynomial)tester.retrieve()).getExp() will return an int equal to 'e.' i tried this:
    System.out.println("e="+e);
    System.out.println((Polynomial)tester.retrieve()).getExp());
    if( e == ((Polynomial)tester.retrieve()).getExp() ){
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    System.out.println( "this.coeff = " + this.coeff );
    with that, the output showed that e and the getExp() output were the same. it also showed (as output) that this.coeff did change in value, but when i tried this:
    System.out.println( ((Polynomial)tester.retrieve()).getCoeff() )
    to check if the value changed within the object, it didn't. this.coeff changed, but the actual coeff variable in the object didn't.
    any ideas?

  • 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.

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Travwerse a linked list in a doubly linked list

    I have to traverse a linked list to a doubly linked list and I am not sure how to do that.
    Here is some sample code:
    class linkData {
              dataRecord data;
              linkData next;
              linkData prev;
    linkData head;Should I use something like this:
    if (index < (size >> 1)) {
                     next = header.next;
                     for (nextIndex=0; nextIndex<index; nextIndex++)
                       next = next.next;
                 } else {
                    next = header;
                     for (nextIndex=size; nextIndex>index; nextIndex--)
                         next = next.previous;
                 }

    mindspeed wrote:
    I have to traverse a linked list to a doubly linked list This makes no sense as traverse means to pass or move over or along something. Perhaps you mean translate instead.

  • Inserting into a linked list

    Hello all,
    I'm currently studying for a midterm on linked lists and I'm having a little trouble inserting in "order". What I'm trying to do is use a compareTo method to compare serial numbers of items. The compareTo methos is as follows:
    public int compareTo(Object obj) {
         StoreItem other = (StoreItem) obj;
         return serialNumber - other.serialNumber;
    And the following is my addItem method....which should simply insert the Node into the list in it's proper place according to it's serial number. Any help would be greatly appreciated:)
    public boolean addItem(StoreItem item){
    if (item == null)
    return false;
    else if (first == null)
    {first = new Node (item, null);
                return true;}
    else {
    Node p = first;
    while (p.next != null && item.compareTo(p.value) > 0){
         p = p.next;
    p.next = new Node (item, p.next);
    return true;
    Thanks again!
    Tyler

    My error lies in the "else {" section of the code....The code up to there works fine as I've tried adding one element to an empty list and print it and it works. What doesn't work is when there's already one item in my list and I want to add another, which is what the following code was meant to do:
    else {
    Node p = first;
    while (p.next != null && item.compareTo(p.value) > 0){
         p = p.next;
    p.next = new Node (item, p.next);
    return true;
    This code compiles and doesn't give me a runtime error, yet when I execute the program, it only seems to add the first element....
    Thanks again for the help:)
    Tyler

  • 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

Maybe you are looking for