Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Linked Lists and Nodes

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Linked Lists and Nodes

    having some problems with my add function it is supposed to add another node to the list in a sorted order but i don't think its working at all and thats why im getting a null pointer exception in my print function. thank you in advance!

    SortedListDriver.java
     
    /**
     * @author lisit
     *
     */
    public class SortedListDriver {
     
        /**
         * @param args
         */
        public static void main(String[] args) {
           SortedLList slist = new SortedLList();
     
          slist.add(1);
          slist.print();
          slist.add(3);
          slist.print();
          slist.add(2);
          slist.print();
          slist.add(5);
          slist.print();
          slist.add(4);
          slist.print();
     
     
     
        }
     
    }

    SortedLList.java
     
     
    /**
     * @author lisit
     *
     * @param <T>
     */
     
    public class SortedLList<T extends Comparable<T>> implements
            SortedListInterface<T> {
     
    	private Node firstNode;
    	private int numberOfEntries;
     
        public SortedLList() {
            Node n = new Node();
     
        }
     
        @Override
        public void add(T newEntry) {
        	Node<T> newNode = new Node(newEntry);
           	if(isEmpty())
        		firstNode = newNode;
        	else
        	{ 
        		Node<T> compareNode = firstNode;
        		for(int i=0; i<numberOfEntries-1; i++){
        			T compareData = compareNode.getData();
        			if(newEntry.compareTo(compareData) > 0){
        				System.out.println("IF STATEMENT WORKED");
        				Node nodeBefore = getNodeAt(i-1);
        				Node nodeAfter = nodeBefore.getNextNode();
        				newNode.setNextNode(nodeAfter);
        				nodeBefore.setNextNode(newNode);
        			}
        			else{
        				compareNode.getNextNode();
        				System.out.println("compareNode " + compareNode.getData());
        			}
        		}
     
        	}
           	numberOfEntries++;
     
        }
     
        @Override
        public boolean remove(T anEntry) {
            // TODO Auto-generated method stub
            return false;
        }
     
        @Override
        public int getPosition(T anEntry) {
            // TODO Auto-generated method stub
            return 0;
        }
     
        @Override
        public T getEntry(int givenPosition) {
            // TODO Auto-generated method stub
            return null;
        }
     
        @Override
        public boolean contains(T anEntry) {
            // TODO Auto-generated method stub
            return false;
        }
     
        @Override
        public int getLength() {
            return numberOfEntries;
        }
     
        @Override
        public boolean isEmpty() {
        	boolean result;
        	if(numberOfEntries == 0){
        		assert firstNode == null;
        		result = true;
        	}
        	else{
        		assert firstNode != null;
        		result = false;
        	}
            return result;
        }
     
        @Override
        public T[] toArray() {
            // TODO Auto-generated method stub
            return null;
        }
     
        @Override
        public T remove(int givenPosition) {
            // TODO Auto-generated method stub
            return null;
        }
     
        @Override
        public void clear() {
        		firstNode = null;
        		numberOfEntries = 0;
     
        }
        public void print(){
        	Node listNode = firstNode;
        	System.out.println("Number of Entries: " + numberOfEntries);
           	for(int i=0; i<numberOfEntries; i++){
        		System.out.println(listNode.getData());
        		listNode = listNode.getNextNode();
        	}
        }
        private Node getNodeAt(int givenPosition) {
            assert !isEmpty() && (1 <= givenPosition)
                    && (givenPosition <= numberOfEntries);
            Node currentNode = firstNode;
            for (int counter = 1; counter < givenPosition; counter++)
                currentNode = currentNode.getNextNode();
            assert currentNode != null;
            return currentNode;
        } 
     
    }

    Node.java
     
     
     
    public class Node<T> {
     
     
    	        private T data;
    	        private Node next;
     
    	        public Node(){
    	        	data = (T) null;
    	        }
     
    	        public Node(T dataPortion) {
    	            this(dataPortion, null);
    	        }
    	        public Node(T dataPortion, Node nextNode) {
    	            data = dataPortion;
    	            next = nextNode;
    	        } 
    	        public T getData() {
    	            return data;
    	        }      
     
    	        public Node getNextNode() {
    	            return next;
    	        } 
     
    	        public void setNextNode(Node nextNode) {
    	            next = nextNode;
    	        } 
     
    }

    output
    Number of Entries: 1
    1
    Number of Entries: 2
    1
    Exception in thread "main" java.lang.NullPointerException
    	at SortedLList.print(SortedLList.java:113)
    	at SortedListDriver.main(SortedListDriver.java:17)

    EDIT:

    SortedListInterface.java
    /**
     * An interface for the ADT sorted list. Entries in the list have positions that
     * begin with 1.
     * 
     * @param <T>
     *            The type of object stored in the sorted list
     */
    public interface SortedListInterface<T extends Comparable<T>> {
        /**
         * Adds a new entry to this sorted list in its proper order.
         * 
         * @param newEntry
         *            the object to be added as a new entry
         */
        public void add(T newEntry);
     
        /**
         * Removes a specified entry from this sorted list.
         * 
         * @param anEntry
         *            the object to be removed
         * @return true if anEntry was located and removed
         */
        public boolean remove(T anEntry);
     
        /**
         * Gets the position of an entry in this sorted list.
         * 
         * @param anEntry
         *            the object to be found
         * @return the position of the first or only occurrence of anEntry if it
         *         occurs in the list; otherwise returns the position where anEntry
         *         would occur in the list, but as a negative integer
         */
        public int getPosition(T anEntry);
     
        /**
         * Retrieves the entry at a given position in this list.
         * 
         * @param givenPosition
         *            an integer that indicates the position of the desired entry
         * @return a reference to the indicated entry or null, if either the list is
         *         empty, givenPosition < 0, or givenPosition > getLength() - 1
         */
        public T getEntry(int givenPosition);
     
        /**
         * Sees whether this list contains a given entry.
         * 
         * @param anEntry
         *            the object that is the desired entry
         * @return true if the list contains anEntry, or false if not
         */
        public boolean contains(T anEntry);
     
        /**
         * Gets the length of this list.
         * 
         * @return the integer number of entries currently in the list
         */
        public int getLength();
     
        /**
         * Sees whether this list is empty.
         * 
         * @return true if the list is empty, or false if not
         */
        public boolean isEmpty();
     
        /**
         * Retrieves all entries that are in this list in the order in which they
         * occur in the list.
         * 
         * @return an array of the entries of this list
         */
        public T[] toArray();
     
        /**
         * Removes the entry at a given position from this list. Entries originally
         * at positions higher than the given position are at the next lower
         * position within the list, and the list's size is decreased by 1.
         * 
         * @param givenPosition
         *            an integer that indicates the position of the entry to be
         *            removed
         * @return a reference to the removed entry or null, if either the list was
         *         empty, givenPosition < 0, or givenPosition > getLength() - 1
         */
        public T remove(int givenPosition);
     
        /** Removes all entries from this list. */
        public void clear();
     
    } // end SortedListInterface


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,163
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Linked Lists and Nodes

    Exception in thread "main" java.lang.NullPointerException
    at SortedLList.print(SortedLList.java:113)
    There is a variable with a null value on line 113. Look at line 113 in the your source and see what variable is null. Then backtrack in the code to see why that variable does not have a valid value.
    If you can not tell which variable it is, add a println just before line 113 and print out the values of all the variables on that line.


    The posted code does not compile without errors because of missing classes.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Linked Lists and Nodes

    sorry about that i added sortedlistinterface.java so it should compile now! and i print out numberOfEntries and i and they both are working correctly but im still getting the output of 1 and 4 4's instead of 1 2 3 4 5

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,163
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Linked Lists and Nodes

    Time to do some debugging. Add some more println statements to show the values of variables as the code executes and as the values of variables change.


    Did you find cause for the error and fix the error?


    One thing I've found useful with linked lists is to add a toString() method to the node class that returns a String with the nodes data and next value. Then any time you print any reference to a node, you will get a full printout of the node's data and next values.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Linked Lists and Nodes

    i put some println statements before i compare anything and in my else statement just to see if i was getting a false positive and at first it works and tries to compare 3 to 1 and then even gets to comparing 2 and it goes through the else statement since 1 is less than 2 but then i get a null pointer exception

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,163
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Linked Lists and Nodes

    then i get a null pointer exception
    add some printlns to show what variable has a null value.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Linked list is not displaying the nodes correctly
    By Jpopto in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 7th, 2013, 02:02 PM
  2. swapping nodes in a linked list
    By ueg1990 in forum Java Theory & Questions
    Replies: 3
    Last Post: September 10th, 2012, 02:37 PM
  3. [SOLVED] Linked Lists
    By lieles in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 6th, 2011, 08:39 AM
  4. Linked Lists
    By Jnoobs in forum Java Theory & Questions
    Replies: 1
    Last Post: October 23rd, 2010, 04:09 PM
  5. Problems in linked lists
    By Hotzero in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 5th, 2010, 09:25 AM

Tags for this Thread