Hi all, I'm creating a LinkedList...I've removed most unnecessary code for simplicity. Here's what I expect to happen. I create a list opject, populate it with an item, get the size (which is 1) the I create a list2 object, populate it with an item and get the size of list again...which I would still expect to be 1, but it is 2...why is that happening? Here is my full code:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; //Needed for scanner class /** * class TestLinkedList - */ public class TestLinkedList { public static void main(String[] args) throws FileNotFoundException{ //Populate list with elements IntLinkedList list = new IntLinkedList(); // list = getListFrom("project2.txt"); //Display original list list.addAfter(4); System.out.println( "The original list size is: " + list.size() + " and contains the elements:"); // displayList( list ); System.out.println(); //Sort list // list = sortList( list ); //Display the sorted list IntLinkedList list2 = new IntLinkedList(); list2.addAfter(5); System.out.println( "The final list size is: " + list.size() + " and contains the sorted elements:"); // displayList( list ); System.exit(0); //End Program }//end method main } /** * class IntLinkedList - */ class IntLinkedList{ private static int size; //the number of elements in the list private static IntNode head; private static IntNode tail; private static IntNode cursor; private static IntNode precursor; // //IntLinkedList // public IntLinkedList(){ }//end IntLinkedList // //compute the number of nodes // public static int size(){ size = 0; for ( cursor = head; cursor != null; cursor = cursor.getLink() ){ size++; } return size; }//end size // //addAfter // public static void addAfter( int value ){ if ( cursor == null ) { // either no current element or current element is first // add element to the head of the list head = new IntNode( value, head ); cursor = head; } else { // cursor points to the middle of the list cursor.setLink( new IntNode( value, cursor.getLink()) ); //cursor = precursor.getLink(); } if ( size() == 0 ) // the list was empty and tail needs to be initialized tail = head; } } /** * class IntNode - */ class IntNode{ // //Variables // private int data; //variable to store an integer value. private IntNode link; //variable to store an IntNode object. // //Non-default constructor to initialize the data fields // public IntNode( int initData, IntNode initLink ){ data = initData; link = initLink; } // //Accessor and mutator methods for data and link fields // public int getData(){ return data; } public IntNode getLink(){ return link; } public void setData(int newData){ data = newData; } public void setLink(IntNode newLink){ link = newLink; } }//end class IntNode
Thanks for any help,
Mason