Linked lists help... how exactly is this a NullPointerException?

So I have a linked list class with variables head and tail both initialized to "null", with variables for size, declare, and traveler (not really relevant to this though). We have to create methods to manipulate said list.
For a test I declared an instance of this linked list:
static SinglyLinkedList list = new SinglyLinkedList();One of the methods we have to create is an append method, here's the code for that:
public void append(Object dataToAdd)
          if(head == null & tail == null)
               head = new Node(dataToAdd, null);
               tail = head;
          else
               tail.next = new Node(dataToAdd, null);
               tail = tail.next;
     }Testing it with...
list.append("A");Gives null pointer exceptions at the if statement in the append method as well as at the list.append line. But why? What is exactly pointing to null?

Ah... I didn't think of head not being null but tail being null.
I initiated the traveler node in the linked list class to head.
then I added this in between the if and else statements I had:
else if(head != null & tail == null)
               while(traveler.next != null)
                    traveler = traveler.next;
               tail = traveler;
               tail.next = new Node(dataToAdd, null);
               tail = tail.next;
                        }But it's still giving me the same errors.
Edited by: klawson88 on Feb 12, 2009 12:32 AM

Similar Messages

  • My Creative Cloud subscription has expired, and I assigned the monthly payment, but I can not open any progam creative cloud, I need help how to solve this problem

    my Creative Cloud subscription has expired, and I assigned the monthly payment, but I can not open any progam creative cloud, I need help how to solve this problem

    Carlos-
    Start by signing out and back in to see if it will see the subscription: 
    How to sign in and sign out of creative cloud (activate/deactivate)
    If the apps are installed fine and close after launch see this link:
    CC applications close immediately after launch
    If the problem is something different, please let us know the error you see or what is happening on the screen so we can advise  you on a solution
    Pattie

  • Hi, when ever I'm using 3G, on my Iphone4 sim stops working and Network is lost, this started after I updated my phone with  6.0.1(10A523)version. Please help how to solve this problem.

    Hi, when ever I'm using 3G, on my Iphone4 sim stops working and network is lost, this started after I updated my phone with  6.0.1(10A523)version. Please help how to solve this problem. Thanks.

    Photos/videos in the Camera Roll are not synced. Photos/videos in the Camera Roll are not touched with the iTunes sync process. Photos/videos in the Camera Roll can be imported by your computer which is not handled by iTunes. Most importing software includes an option to delete the photos/videos from the Camera Roll after the import process is complete. If is my understanding that some Windows import software supports importing photos from the Camera Roll, but not videos. Regardless, the import software should not delete the photos/videos from the Camera Roll unless you set the app to do so.
    Photos/videos in the Camera Roll are included with your iPhone's backup. If you synced your iPhone with iTunes before the videos on the Camera Roll went missing and you haven't synced your iPhone with iTunes since they went missing, you can try restoring the iPhone with iTunes from the iPhone's backup. Don't sync the iPhone with iTunes again and decline the prompt to update the iPhone's backup after selecting Restore.

  • In iTunes 11, when I click on "Artists," several "Album Artists" show up in list.  How to correct this?  Thanks!

    Hello,
    When I click on "Artists," a number of "Album Artists" are showing up in the list.  How to correct this?  Thank you!

    Is that the Bookmarks Menu button ?
    *https://support.mozilla.org/kb/how-do-i-use-bookmarks
    *https://support.mozilla.org/kb/common-questions-after-updating-firefox
    *http://kb.mozillazine.org/Sorting_and_rearranging_bookmarks_-_Firefox
    *https://support.mozilla.org/kb/Sorting+bookmarks

  • HT204321 i am getting a pink blur link in sunlight how to fix this i had been updated my ios to 8.2 i faced this problem in ios 8.1.3

    i am getting a pink blur link in sunlight how to fix this i had been updated my ios to 8.2 i faced this problem in ios 8.1.3

    Please define "pink blur link."  iOS 8.3 is the current version.

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Linked List Help!

    Hi,
    I have an assignment on linked lists, as a beginner I am really struggling with it for hours...
    I have to write the following methods without importing any libraries.
    "Write an iterative method delete() for LinkedStackOfStrings that takes an integer parameter k and deletes the kth element (assuming it exists).
    Write a method find() that takes an instance of LinkedStackOfStrings and a string key as arguments and returns true if some node in the list has key as its item field, false otherwise."
    It must be implemented in the code on this site:
    [http://www.cs.princeton.edu/introcs/43stack/LinkedStackOfStrings.java.html]
    Help would be appreciated! I have been trying for hours :(

    vdL wrote:
    Thanks for the reply! Yes, I forgot add what my actual problem is.
    If I am correct, I will need to be able to traverse through the list up to a certain point, redirect and redirect the pointers.
    My problem is I am able to traverse through the list using 'for(Node x = first; x != null; x= x.next)' but I do not know how make it only run up to a particular position in the list.You can keep an integer counter, increment it each time through the loop, and break out of the loop when the counter is big enough. Example of breaking:
    if (n == k) break;
    And also, how not to loose the previous Node when traversing trough the list.You're allowed to have multiple references. So you could keep one reference to the current node, and one reference to the one before it.
    Or, rather than looping through the list until you find the kth element, loop until you find the (k - 1)th element, then (if it exists) remove the one after it.

  • 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

  • Java Linked List Help

    Hey,
    I am having trouble understanding the Linked List implementation code given under the Node Operations part of this pdf.
    http://www.cs.berkeley.edu/~jrs/61b/lec/07.pdf
    public ListNode(int item, ListNode next) {
    this.item = item;
    this.next = next;
    public ListNode(int item) {
    this(item, null);
    ListNode l1 = new ListNode(7, new ListNode(0, new ListNode(6)));
    I understand the earlier implementation, but this one has me confused. Would someone please go through/explain the flow of this implementation with me?
    Thanks

    Well the code is pretty self explanitory.
    a ListNode class that has two fields. an int field item, and a ListNode field next.
    so when you create a ListNode object you can do so by one of two means passing one parameter or passing two parameters.
    if you pass one parameter then you have a ListNode which has an int say 1 and a ListNode object who's value is null.
    if you pass two parameters then you have a ListNode which has an int say 2 and a ListNode object who's value is the ListNode you pass to it.
    ex ListNode myNode = ListNode(1,new ListNode(2));
    so myNode now has an integer 1 and a reference to another ListNode which has an integer value of 2 and a reference to a null ListNode.
    hope this helps.

  • Array of Linked List Help

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

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

  • Link list help

    Hi, I am implementing a graph for my Java project and part of the coding requires link list for the edges.
    I wrote the code, but I just don't understand why it does not function the way like it is in C++.
    Bascilly, I have trouble adding data into a linklist
    My codes are as follows:
    public int insertLink(String fCity, String tCity, int distance)
         int location = find(fCity);
         if(location == -1)
              return -1;
         else
         insertNode(new Link(tCity,distance), location);
         return 0;     
    private void insertNode(Link node, int index)
              Link head = vertex[index].head;
              while(head != null)
                   head = head.next;
              head = node;
    This is to add stuff to the list, but for some reason, when i try to display the data, i keep getting null. somehow when
    head = node
    head = new Link(data, data);
    the head points to somwhere else, and not refer to the linklist vertex[index].head anymore...
    Here is my code to display my data:
    public void printVertex()
         for(int i = 0; i < vertex.length; i++)
              if(vertex[i] != null)
                   System.out.print(vertex[i]+" --");
                   Link node = vertex.head;
                   while(node != null)
              System.out.print(node.toCity+","+node.distance+"--");
                             node = node.next;
                   System.out.println();
    Am i doing something wrong so my linklist isn't implement correct?
    THank you.

    Hi, the "fix" for head.next != null didn't work
    private void insertNode(Link node, int index)
              Link head = vertex[index].head;
              while(head != null)
                   head = head.next;
              head = node;
              System.out.println(head.toCity+","+head.distance);
              System.out.println(vertex[index].head.toCity+","+vertex[index].head.distance);
         }basiclly. When i do System.out.println(head.toCity+","+head.distance);, it can display data
    but System.out.println(vertex[index].head.toCity+","+vertex[index].head.distance);
    it throow null's error.
    Btw, yes , i know Java have build in Link list, but unfortunately, my professor likes to reinvent the wheel and want us to do everything from scratch...
    So any other help will be useful, thank you.

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

  • "In material transfer profit centre link is mandatory" how to do this

    Hi Friends,
    How to do this validation , can any one guide me.
    "In material transfer profit centre link is mandatory"
    Regards
    Mahesh A

    Hi
    While creating material choose costing view1,you will find there profit center its required field there,maintain costing view1 to material master all your material master and maintain profit center it will come automatically in grn accounting doc and same you can see in accounting tab
    Regards
    Kailas ugale

  • Circular Doubly-linked list: Cannot seem to get this working. Please help!

    Hello, I am trying to implement a CDLL of Node objects that look like: (null/char/char/null);
    here are my Node and List (called cipher) constructors & insert() method:
    Node constructors:
         //     Default constructor
         //     -Takes no args
         //     -Assigns plaintext val to ''
         //     -Assigns cipher val to ''
         //     -Assigns left & right pointers to null
         public Node() {
              previous = null;
              plaintext = ' ';
              ciphertext = ' ';
              next = null;
         }//end default constructor
         //      Constructor 2
         //     -Assigns left & right pointers to null
         //     -Parameter: char newPlaintext: the plaintext value to be assigned to the Node
         //     -Parameter: char newCipher: the cipher value to be assigned to the Node
         public Node(char newPlaintext, char newCipher) {
              previous = null;
              plaintext = newPlaintext;
              ciphertext = newCipher;
              next = null;
         }//end constructor 2List Constructor:
         public Cipher() {
              //Create the Node coder with empty elements that points to itself
              sentinel = new Node(' ', ' ');
              //coder points to itself in both directions
              sentinel.setNext(sentinel.previous);
              sentinel.setPrevious(sentinel.next);
              //Set pointer to the node created
              current = sentinel;
         }//end Cipher() defalut constructorinsert() method:
    public static void insert(char thePlaintext, char theCiphertext) {
              Node temp = new Node(thePlaintext, theCiphertext);
              if (isEmpty()) {
                   System.out.println("          in the isEmpty area of insert");
                   current = temp;    
                   sentinel = temp;
              }else {
                   System.out.println("          in the not empty area of insert");
                   Node p = current.getNext();
                   current.setNext(temp);
                   temp.setPrevious(current);
                   temp.setNext(p);
                   p.setPrevious(temp);
                   p = current.getNext();
                   current = temp; //Set last pointer to point to x
                   System.out.println("Current.plaintext is: "+current.plaintext);     
                   System.out.println("p.plaintext is: "+p.plaintext);     
                   current = temp; //Set last pointer to point to x
              }//end ifI'm thinking that the problem is something relatively simple... I just can't seem to get it right.
    Can somebody please tell me what's wrong w/ this data structure?
    Thanks in advance to everyone.

    Hello there, BrenFire.
    The following Knowledge Base article provides assistance with downloading your purchased content:
    Downloading past purchases from the iTunes Store, App Store, and iBooks Store
    http://support.apple.com/kb/HT2519
    Particularly:
    TV Shows
    Make sure you're signed in with the same Apple ID you used for the original purchase.
    Tap the Videos app.
    Tap TV Shows, at the bottom of the page.                                                                                                 
    Find and tap the show and season you want to download.
    Tap the download icon next to the episode you want to download.
    The TV show will begin downloading.
    Thanks for reaching out to Apple Support Communities.
    Cheers,
    Pedro.

  • Adobe InDesign CC looses links randomly. How to correct this ?

    Hi
    InDesign CC looses links randomly. I need to update them regularly, and then they get lost again and so on. Hence my question: how to avoid that ?
    PS: I was previously working on Indesign CS4, and never had this issue.
    Thanks

    Basically, when i open the file, everything is fine.
    1 - Then, the ‘warning’ icon appears on 1 link, then 2, until all links are lost.
    2 - I then need to update these links. To do so, I select the links in the links panel, right click, and then click ‘update link’.
    3 – then, after a while, links start to get lost again, so back to 1.
    I have to mention that I don’t have these issues with all files, but with around 4-5 of them.
    Everything was working fine when I was on CS4, it just appeared when I switched to CC.
    Hoping this can help understanding…

Maybe you are looking for

  • Family sharing actually is not Family but App Store sharing

    I convinced my mother to purchase a brand new iPhone 6 because of the many features iOS and the whole Apple environment brings to the table. One of those features would be Family sharing. Turns out it's not working due to a hidden restriction that Ap

  • View for procedures parameters

    Hello. Is there any view (the kind of dba_procedures) where the parameters of the procedures can be found? Thanks in advance.

  • The document could not be saved. A file error has occurred.

    I opened an Adobe Reader PDF form that I can save data on from a folder in my computer and now it won't let me save any of the changes I made to it. I know I have been able to save my changes in the past, but now it continues to give me this error me

  • HDMI Out memory full errors

    Almost every time I go to play my HD videos i recorded via the HDMI out port, i get memory full errors. Even when there are no apps running in the background. Some times a reboot will help, but not always. Is this a bug?

  • Repository Size

    Hi all, Is there any tcode or report to calculate a repository size. In this case its SOFFDB (SAPOffice docs) stored in the database. Regards