Long Linked List

is it possible to create a Linked List with a long as it's counter?

Sure, just write the code yourself. But why? Do you intend to have more than 2 billion elements in a linked list?

Similar Messages

  • HELP!!  I viewed my "backup" files, and now ALL of my photos are no longer "linked" to Lightroom.

    I thought I was missing some files, so I viewed my backup files.  I received a "warning" that Lightroom would restart and view my backup files.  I did NOT receive any warning, that there was NO GOING BACK!!  I've tried everything.  I cannot re-link ANY of my photos.  Well, I did just do one, and it told me all the other photos in the folder were corrupt and Lightroom would not be able to edit them (and no, it was not an exported .jpeg file).  Fortunately, I am not concerned about this folder, that's why I tested it.  I was forced to moved all of my photos from my C drive to my D drive because for some weird reason on this computer, my D drive is 5 times bigger and I ran out of room.  When I did that, I was able to relink all the pictures.  Sadly, it didn't keep my Folders, it just relinked them all by date.  That I can deal with, even though it makes finding photos much more difficult, but I wasn't about to try to rename any of them and have to relink again.
    Now, I can't relink any of them because it appears in Lightroom that all photos are back in the C drive and therefore, the new photos that I placed on the D drive are not there, and nothing will relink, period, not even the ones that were originally on my C drive!
    I have never been so aggravated in my life.  I LOVE Lightroom capabilities.  I have version 2.3.  When I look it up on the online help, all I get is how the photos are in whatever location they were saved, but they are linked, etc.  I already know that part.  I seriously wish I had NEVER looked at my backup files.  I don't think I'll bother backing up stuff anymore because apparently looking at the backup messes up everything.
    I fully anticipated that I would be able to go back, choose my folders on my D drive and have all of my current photos available.  Sadly, not.
    My user name should be FREAKED OUT!

    Thanks!  I've been practicing deep breathing between yelling at my computer.  I use Windows 7.  I was in my "regular" Lightroom photos, and I couldn't locate some pictures I took last December.  So, I thought, well, why not look at the back up files?  I'm normally excellent at remembering exact steps, but I'm so worried about all of my thousands of photos, I can only explain what I think I did.  I went into Windows Explorer, and chose the backup files.  When I did, I received the warning about Lightroom restarting and loading the backup photos.  I hesitated for a full minute, but thought, well, isn't that what backup files are for?  So, I selected it. Lightroom opened the backup photos without any problem.  But, when I went back, and tried opening the photos that were linked to Lightroom, they were no longer linked.  When I click on the formerly linked photos, they just open in Windows Explorer, not Lightroom.  When I open Lightroom, it has says all the photos are "missing."  All of the folders are listed in my C drive (in Lightroom), not where they'd been moved to on my D drive.  The one photo I relinked, stated the photos in that folder could not be edited in Lightroom.  So, I'm afraid to try to relink anymore of them. Also, as I said, any photos that I originally imported to my D drive are not showing up in Lightroom at all.
    I would say, I normally learn software quickly. That was my experience with Lightroom.  I installed it, went through all of the online training sessions, and have loved it.  Admittedly, I'm sure there are features that I don't make use of that many people do, but I'm just a passionate photography nut, not a professional.
    The online help basically explains the linking, and even how to relink if you "move" a file, a folder to another location.  It doesn't cover this, or not where I can find it.
    I've think I've given up on yelling at the computer, now I just have knots in my stomach about getting photos relinked.  I have probably 80% of them exported, with the adjustments I made, but that does not make me feel one bit better.
    Thanks!!!

  • Write two functions to find the the number of elements in a linked list?

    I am trying to Write two functions to find the the number of elements in a linked list. One method using recursion and One method using a loop...
    //The linked List class is Represented here.
    public class lp {
    public int first;
    public lp rest;
    public lp(int first1, lp rest1)
    first = first1;
    rest = rest1;
    The program i wrote so far is
    import java.util.*;
    import linklist.lp;
    public class listCount{
    //loop function
    public static void show_list(lp list)
    int counter = 0;
    while(list != null)
    list = list.rest;
    counter++;
    System.out.println ("length computed with a loop:" + counter);
    //recursive function
    public static int recursive_count(lp list)
    if (list.first == null)
    return 0;
    else
    return recursive_count(list.rest) + 1;
    //main method
    public static void main (String args[])
    lp list1 = new lp(1, new lp(2, new lp(3, null)));
    show_list(list1);
    System.out.println("length computed with a recursion:" +
    recursive_count(list1));
    at the if (list.first == null) line i get the error " incomparable types:
    int and <nulltype>" I know this is a beginners error but please
    help...What should I do?

    byte, char, short, int, long, float, double, and boolean are primitives, not objects. They have no members, you cannot call methods on them, and they cannot be set to or compared with null.

  • 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

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

  • Object linked list

    Hi am trying to create a linked list out of an object i have called ClassID.
    I have a Link class (that creates a node correct?):
    import java.io.*;
    public class Link
         public ClassID id;
        public Link next;
         public Link(ClassID inID)
              this(inID, null);
        public Link(ClassID inID, Link next)
            id = inID;
            next = next;;
         public void displayLink() // display ourself
              id.toString();
    } // end class LinkIf it does create node then I have a class called LinkList with the following insert method:
    private Link first; // ref to first link on list
    // insert at start of list
         public void insertFirst(Link id)
         { // make new link
              Link newLink = new Link(id);
              newLink.next = first; // newLink --> old first
              first = newLink; // first --> newLinkBut it doesnt seem to be working, could someone help me.
    Thanks
    Phil
    Edited by: The_One on Sep 13, 2008 1:49 AM

    I dont think its doing it properly. Iv tried goign through it but cant find the problem. Might be a problem with displaylist
    Let me paste all my classes:
    LINK METHOD:
    import java.io.*;
    public class Link
         public ClassID id;
        public Link next;
         public Link(ClassID inID)
              this(inID, null);
        public Link(ClassID inID, Link next)
            id = inID;
            next = next;;
         public void displayLink() // display ourself
              id.toString();
    } // end class LinkLINKLIST METHOD:
    class LinkList
         private Link first; // ref to first link on list
         public LinkList() // constructor
              first = new Link(null); // no items on list yet
         public boolean isEmpty() // true if list is empty
              return (first==null);
         // insert at start of list
         public void insertFirst(ClassID id)
         { // make new link
              Link newLink = new Link(id);
              newLink.next = first; // newLink --> old first
              first = newLink; // first --> newLink
    public void displayList()
              System.out.print("List (first-->last): ");
              Link current = first; // start at beginning of list
              while(current != null) // until end of list,
                   current.displayLink(); // print data
                   current = current.next; // move to next link
              System.out.println("");
    ................. SOME MORE METHODS..........MAIN METHOD:
    import java.io.*;
    public class SortListApp
        public static void main(String[] args)
         BufferedReader inputStream = null;
         LinkList list = new LinkList();
         try
              inputStream = new BufferedReader(new FileReader("data.txt"));
               String inName;
              int inIDNum;
              int inACNum;
              long inTime;
              int inTransmode;
              //while ((inName = (inputStream.readLine()) ) != null)
                   inName = inputStream.readLine();
                   inIDNum = Integer.parseInt(inputStream.readLine());
                   inACNum = Integer.parseInt(inputStream.readLine());
                   inTime = Long.parseLong(inputStream.readLine());
                   inTransmode = Integer.parseInt(inputStream.readLine());
                   list.insertFirst(new ClassID(inName, inIDNum, inACNum, inTime, inTransmode));                    
              list.displayList();
              //System.out.println("Printed to file");
              //list.sort();
              inputStream.close();
         catch (IOException error)
              System.out.println("Error in file");
    }Edited by: The_One on Sep 13, 2008 2:41 AM

  • Trouble importing third party classes & using linked list in j2me

    Hi!
    I need to use the linked list data structure in a j2me application im developing. Al long as I know, it is not included in standard libraries.
    I found the "workaround", the substitution in Jade Laepaddon. This is actually a set of classes in a directory.
    I know this is extremely dumb, but I have no luck impotring these classes in my project.
    Im using the WTK2.0 to compile and execute the application, but I don't have an Idea how to add a directory in the CLASSPATH.
    So, the actual question should be: how to include a directory of files, so that it can be imported with:
    import dirName.*;
    Thanks!

    Tha import problem is solved, but I'm still not able to use the LinkedList class. In the jade/util/leap there is a LinkedList.java file, but I get an error :
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: class LinkedList is public, should be declared in a file named LinkedList.java
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class List
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class Serializable
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/Iterator.java):41: class Iterator is public, should be declared in a file named Iterator.java
    (source unavailable)
    when initialising an LinkedList type object.

  • My bank card will no longer link to my billing information when it has previously worked; I'd like to know why this is happening and how to resolve it

    My bank card will no longer link to my billing information when it has previously worked; I'd like to know why this is happening and how to resolve it

    Do you mean that it's being declined, that you are getting an error message, ... ?
    If it's a debit card then I don't think that they are still accepted as a valid payment method - they are not listed on this page and there have been a number of posts recently about them being declined
    If it is a credit card then is it registered to exactly the same name and address (including format and spacing etc) that you have on your iTunes account, it was issued by a bank in your country and you are currently in that country ? If it is then you could check with the card issuer to see if it's them that are declining it, and if not then try contacting iTunes support and see if they know why it's being declined : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page

  • Linked lists revisited

    hi i have the base code for a linked list implementation:the list, the node, and the iterator position. But the assignment gets harder i have to use this class and have a file read in from the command line and store each word into nodes. I can almost implement this with the String Tokenizer and the buffereader stuff but my other problem comes when i have to represent a arbitrarily long integer value in nodes. Basically i must represent the addition or multiplication of a number such as 50003401 and represent it in nodes storing the coefficient and the exponent so like (5*10^7)+(3*10^3)+(4*10^2)+(1*10^0). I need some help!! How do you store the coefficients and exponents in nodes and have them multiply and deal with all the carries.

    Here is my code with spaces in between each class
    import java.util.*;
    import java.io.*;
    public class SortedLinkedList
    SortedListNode header; //The list header, references a SortedListNode
    // constructor: should initialize to an empty list.
    public SortedLinkedList()
         header= new SortedListNode(null);//
    // returns an iterator that references the head of the list
    public SortedLinkedListItr zeroth( )
         return new SortedLinkedListItr(header);//
    // returns true if the list is empty, false otherwise
    public boolean isEmpty( )
         return header.next == null;
    // returns an iterator that references the first item in the list
    public SortedLinkedListItr first( )
         return new SortedLinkedListItr(header.next);//
    // inserts the item referenced by x into the list in sorted order.
    public void insert(Comparable x)
         SortedLinkedListItr prev=zeroth();//
         SortedLinkedListItr curr=first();//
              while(curr!=null && x.compareTo(curr.retrieve())>0)
                   prev.advance();
                   curr.advance();
              insert(x);
    // returns an iterator that references the item x if it is found in the list
    public SortedLinkedListItr find(Comparable x)
         SortedListNode itr= header;//
         while( itr.next != null && !itr.next.element.equals(x))
              itr=itr.next;
              return new SortedLinkedListItr( itr );//
    // returns an iterator that references the item that precedes x in the list
    // (if such an item exists).
    public SortedLinkedListItr findPrevious(Comparable x)
         SortedListNode itr = header;//
         while(itr.next !=null && !itr.next.element.equals(x))
              itr = itr.next;
         return new SortedLinkedListItr(itr);//
    // removes the item x from the list, if it exists
    public void remove(Comparable x)
         SortedLinkedListItr p =findPrevious(x);//
         if ( p.current.next !=null )
         p.current.next = p.current.next.next;
    // prints the items in the list in the order that they appear in the list
    public void printList()
         if(isEmpty())
              System.out.print("The list is empty.");
         else
              SortedLinkedListItr itr = first();//
              for(; itr!=null; itr.advance())
                   System.out.print(itr.retrieve() + " ");
         System.out.println();
    public static void main(String[] args) throws IOException
              SortedLinkedList stringList = new SortedLinkedList();
              if (args.length != 1)
                   System.err.println("USAGE: java ReadData input-file\n");
              System.exit(1);
              String filename = args[0];
              FileReader fileReader = new FileReader(filename);
              BufferedReader bufferedReader = new BufferedReader(fileReader);
              System.out.println(filename + " has the following tokens in it:");
              String inputString = bufferedReader.readLine();
              while (inputString!=null)
              StringTokenizer tokenizer = new StringTokenizer(inputString);
              while (tokenizer.hasMoreTokens())
              String token = tokenizer.nextToken();
              stringList.insert(token);
                        inputString = bufferedReader.readLine();
              stringList.printList();
    public class SortedLinkedListItr
    SortedListNode current; //the node referenced by the iterator.
    //constructor: to be used within SortedLinkedList. Sets the iterator
    //to reference the node specified in the parameter.
    SortedLinkedListItr(SortedListNode theNode)
         current = theNode;
    //returns true if the iterator has advanced past the last node in the list.
    public boolean isPastEnd( )
              return (current == null);
    //returns the item currently referrenced by the iterator (null if the iterator
    //is past the end of the list.
    public Comparable retrieve( )
              if(
              return (current.element);
    // moves the iterator to the next item in the list (does nothing if the
    // iterator is past the end of the list.
    public void advance( )
              if (current!=null)
              current = current.next;
              else
              current=null;
    class SortedListNode
    // instance variables
    Comparable element; // the element being stored by this node
    SortedListNode next; // reference to the next item in the list
    //two constructors, one returns a null next, the other allows
    //it to be set to reference another node.
    SortedListNode(Comparable theElement)
              this(theElement, null);
    SortedListNode(Comparable theElement,SortedListNode n)
              element=theElement; next = n;
    }

  • Linked Lists with Arrays

    I am setting up a linked list of the following very simplified class:
    class LinkedList
         String Name=" ";
         double ID=0;
         static long next=0;
    }the main class is as follows:
    class Links
         public static void Display(LinkedList Link)
         /** A Display function that simply displays everything within the LinkedList class*/
         System.out.println("\nName: " + Link.Name +"\nID  #: " + Link.ID + "\nNext ID: " + Link.next);
         public static void main(String[] args)
              int MAX_LINKS=10;
              LinkedList[] Link=new LinkedList[MAX_LINKS];
              for (int i=0;i<MAX_LINKS;i++)
                   Link.ID=i;
                   Link[i].next++;
                   Display(Link[i]);
    everything compiles fine, but at runtime I recieve a
    Exception in thread "main" java.lang.NullPointerException
    at Links.Display(Links.java:6)
    at Links.main(Links.java:18)What am I doing wrong?
    Thanks in advance.

    public static void main(String[] args){
       int MAX_LINKS=10;
    // this tells the compiler that the Link array will hold
    //LinkedList objects, but doesn't actually create those objects...
       LinkedList[] Link=new LinkedList[MAX_LINKS];
       for (int i=0;i<MAX_LINKS;i++){
    //NEED TO ADD THIS LINE to create the objects:
          Link[ i ] = new LinkedList();
          Link[ i ].ID=i;
          Link[ i ].next++;
          Display(Link[ i ]);

  • Link List question

    This is more of a development question rather than programming I hope its not wrong to post it here. I apologize if I did
    I am developing a Linked List class that handles a list however, there is a potential (in fact almost a certainty) that the nodes could call to itself and cause an endless loop if running through the it. Any suggestion on how to handle such a case ?

    It's kind of hard to say without more details, but the two general approaches that pop to mind are:
    1) Document it. If the user chooses to ignore the docs, they get bad--posisbly undefined--behavior, and that's their problem.
    2) On every relevant operation, do a search for cycles. Keep track of which nodes you've touched so far. Since the size of the list (and hence the length of a cycle) is theoretically unbounded, and searching every possible path for cycles in a large or complex list (which sounds more like a graph than a list) can take mucho time and/or memory, you'll have to set an upper bound on how deep you'll search. If there's a cycle whose path length is longer than this depth, then you're back to #1 anyway.

  • Is my code a Linked Lists or not?

    Hello everyone,
    [I hope I am in the right forum]
    I am trying to learn how to implement Linked Lists with Java. I have written a small code and I would appreceate it a lot if any one would be kind enough to check if this code is really a linked list.
    I tried to make a list with 3 nodes, with no helping methods for adding and removing nodes. Just a simple example. This is my code:
    public class myList{
         public static final long serialVersionUID = 24362462L;
         //node pointer important to define private, so not share same value
         private myList pointer;
         //node data
         private String nodeData;
    public static void main(String args[]){
    //Give memory to nodes
    myList Node1 = new myList();
    myList Node2 = new myList();
    myList Node3 = new myList();
    //Make Node1
    Node1.pointer = Node2;//give value to pointer
    Node1.nodeData = "Hi i am data contained in Node 1.";
    //Make Node2
    Node2.pointer = Node3;
    Node2.nodeData = "Hi i am data contained in Node 2.";
    //Make Node3
    Node3.pointer = null;
    Node3.nodeData = "Hi i am data contained in Node 3.";
    //Display Data
    System.out.println(Node1.nodeData);
    System.out.println(Node2.nodeData);
    System.out.println(Node3.nodeData);
    //Display pointers
    System.out.println("Hi this is Node2 ==============>:"+Node2);
    System.out.println("This is the value of pointer of Node1:"+Node1.pointer);
    System.out.println("Hi this is Node3===============>:"+Node3);
    System.out.println("This is the value of pointer of Node2:"+Node2.pointer);
    }//main
    }//class
    /***** OUTPUT ***** OUTPUT ***** OUTPUT ***** OUTPUT *****
    Hi i am data contained in Node 1.
    Hi i am data contained in Node 2.
    Hi i am data contained in Node 3.
    Hi this is Node2 ========================>:myList@16f0472
    This is the value of pointer of Node 1 ==>:myList@16f0472
    Hi this is Node3 ========================>:myList@18d107f
    This is the value of pointer of Node 2 ==>:myList@18d107f
    Press any key to continue...
    Thank you very much,
    JMelsi

    Happy to advise. Here we go. :)
    Firstly, you'll want to post your code in code tags. They make your code more legible, thus making it easier and therefore more likely that someone responds. ;)
    Second, it would be more appropriate for class names (such as "myList") to start with an upper-case letter (such as "MyList"). Additionally, the class in question does not represent a whole list but instead a node, so you might want to call it "MyListNode" or something similar.
    Strictly speaking, your code is definitely that of a linked list of nodes. For example, one could print all of the contents in your list with code like this:
    myList node = ...; // assign to the first node
    while (node!=null) // as long as there is a node
        System.out.println(node.nodeData); // print the data in this node
        node = node.pointer; // move on to the next node
    }Note that, in the above code, I didn't have to know how many nodes were in your list or have any references to them beforehand. :) That's the power in the data structure you're creating.
    Enjoy!

  • Baffling linked list error in C program

    I've been working at porting some programs over to a Mac that were built using MS C 6.0.  One of the programs uses a linked list to hold some data.  Just couldn't get it to work.  So I decided to run a really simple test.  Create a short linked list and then print out the list.
    The code is below and the output is below that.  It looks like all the nodes get created properly and pointers assigned correctly but when I print out the list it crashes after the second node everytime.  It appears that in node 2 the link to the next node has been corrupted but I can't see anywhere that happens.  Is this not the way xcode does linked lists?
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    struct linklist {
        int node_number;
        char node_name[10];
        struct linklist * next;
    struct linklist * makenode();
    int main(int argc, const char * argv[])
        struct linklist * list_head;
        struct linklist * list_item;
        int i;
        // insert code here...
        printf("Hello, World!\n");
        list_head = makenode();
        list_head->node_number = 1;
        strcpy(list_head->node_name, "node 1");
        list_head->next = NULL;
        list_item = list_head;
        printf("head-> %0lx, item-> %0lx \n", (unsigned long) list_head, (unsigned long) list_item);
        for (i = 1; i < 10; i++)
            list_item->next = makenode();
            printf("New Node %d at %lu\n", i+1, (unsigned long) list_item->next);
            list_item = list_item->next;
            list_item->node_number = i+1;
            sprintf(list_item->node_name, "node %d", i+1);
            list_item->next = NULL;
            printf("list_item points at %lu\n", (unsigned long) list_item);
        list_item = list_head;
        for (i = 0; i < 10; i++)
            printf("list_item -> %lu>\n", (unsigned long) list_item);
            printf("%d - %s>\n", list_item->node_number, list_item->node_name);
            list_item = list_item->next;
        return 0;
    struct linklist * makenode()
        return (struct linklist *) (malloc( sizeof(struct linklist())));
    Output>>>>>
    Hello, World!
    head-> 7fdf604000e0, item-> 7fdf604000e0
    New Node 2 at 140597369256496
    list_item points at 140597369256496
    New Node 3 at 140597369256512
    list_item points at 140597369256512
    New Node 4 at 140597369256528
    list_item points at 140597369256528
    New Node 5 at 140597369256544
    list_item points at 140597369256544
    New Node 6 at 140597369256560
    list_item points at 140597369256560
    New Node 7 at 140597369256576
    list_item points at 140597369256576
    New Node 8 at 140597369256592
    list_item points at 140597369256592
    New Node 9 at 140597369256608
    list_item points at 140597369256608
    New Node 10 at 140597369256624
    list_item points at 140597369256624
    list_item -> 140597369241824>
    1 - node 1>
    list_item -> 140597369256496>
    2 - node 2>
    list_item -> 7306087013738872835>

    Change
    return (struct linklist *) (malloc( sizeof(struct linklist())));
    to
        return (struct linklist *) (malloc( sizeof(struct linklist)));
    Hello, World!
    head-> 100103b10, item-> 100103b10
    New Node 2 at 4296031024
    list_item points at 4296031024
    New Node 3 at 4296031056
    list_item points at 4296031056
    New Node 4 at 4296031088
    list_item points at 4296031088
    New Node 5 at 4296031120
    list_item points at 4296031120
    New Node 6 at 4296031152
    list_item points at 4296031152
    New Node 7 at 4296031184
    list_item points at 4296031184
    New Node 8 at 4296031216
    list_item points at 4296031216
    New Node 9 at 4296031248
    list_item points at 4296031248
    New Node 10 at 4296031280
    list_item points at 4296031280
    list_item -> 4296030992>
    1 - node 1>
    list_item -> 4296031024>
    2 - node 2>
    list_item -> 4296031056>
    3 - node 3>
    list_item -> 4296031088>
    4 - node 4>
    list_item -> 4296031120>
    5 - node 5>
    list_item -> 4296031152>
    6 - node 6>
    list_item -> 4296031184>
    7 - node 7>
    list_item -> 4296031216>
    8 - node 8>
    list_item -> 4296031248>
    9 - node 9>
    list_item -> 4296031280>
    10 - node 10>
    Program ended with exit code: 0

  • Help with copying contents of file to link list please

    Hi,
    Below is a snippet of code I am playing with. As you can see I have created a LinkList, I now need to copy the contents of a csv file in to that list. The file is several lines long and I need each line in the list.
    I know how to add to the list manually i.e.,
    list.add("First entry in list");
    Could someone help me out with this please.
    Many thanks.
    (***CODE***)
    private LinkedList list = new LinkedList();
         public LinkTest()
              // ** List content START **
              // Open the file today.csv
              File inFile = new File("C:\\today.csv");
         // Create a file stream, wrapping the file
         FileReader fileReader = new FileReader(inFile);
         // Create a second wrapper,
    BufferedReader bufReader = new BufferedReader(fileReader);
         // Read in the first line...
         String s;
         s = bufReader.readLine();
         list.add(s);
         StringTokenizer st = new StringTokenizer(s);
         while (st.hasMoreTokens())
    System.out.println(st.nextToken());
         // ** List content END **
         

    I looked at your code and I thought, what's the question for, it's already adding lines to the list. And then I looked again and had the same thought. The third time I looked I noticed you didn't code the loop that read all the lines from the file. Silly me, I thought your question had something to do with linked lists.
    Anyway, to answer your real question, which is how do you read all the lines from a text file:while ((s = bufReader.readLine()) != null) {
      // do something with the String s here
      // such as adding it to a linked list
    }

  • 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

Maybe you are looking for