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.

Similar Messages

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

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

  • 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

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

  • 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

  • Java Linked List

    public class outlier2D
    double cord[];
    int dim ;
    outlier2D next;
    outlier2D()
    next=null;
    void create_Dim(int k)
    cord=new double[k];
    public static void main(String args[])
    double[] iLine = new double[dim];
    outlier2D curr=null;
    outlier2D node1=null;
    while(((record = br[0].readLine()) != null))
    iLine[0] = new Double(record).doubleValue();
    iLine[1] = new Double(br[1].readLine().trim()).doubleValue();
    outlier2D newobj=new outlier2D();
    newobj.create_Dim(dim);
    newobj.cord=iLine;
    if(node1==null)
    node1=newobj;
    curr=newobj;
    else
    curr.next=newobj;
    curr=curr.next;
    The "node1" and "curr" are 2 objects to the class "outlier2D" which is supposed to be the List class.node1 is the head object. When i access the value for node1 in the if statement i get the first value as the result.
    But when i access the value outside the while loop after inserting all the data,my head object moves to the last data.........
    I would appreciate if anybody could help me with this as i have been trying to find this from past 2 days.
    Thank you

    Your creation of the linked list appears to be correctly coded. However, you appear to have a few other problems.
    1) You haven't set dim.
    2) Is outlier2D your main class? If so your main(String [] args) method is outside of any class. Just a typo?
    3) (And this is probably the root of your problem.) Every instance of your outlier2D class has cord set to iLine! You go to the trouble of creating a new double array in your create_Dim(int k) method and setting cord to point to it but then replace it in your while loop by setting cord to point to iLine.
    Remember that arrays are Objects and the name of the array is a pointer to the object. By writing:
    newobj.cord = iLine;
    you are setting every instance of cord to point to the same instance of iLine.

  • 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

  • Qns Java Linked List

    how do i actually go about sorting a linkedlist using bubble sort. i have tried to move the data to an array than use a bubble sort to sort the array but the java application give me a java null pointer exception

    here is the part where i pass in the array for the bubblesort to sort the data.
    while ((txt=bfr.readLine())!=null){
                        // break the string up into tokens
                        st = new StringTokenizer(txt,",");
                        int i = 0;
                        while (st.hasMoreTokens()){
                             s[i++] = st.nextToken();
                        //System.out.println(s[1]);
                        ll.add(s[1]);
                        ll.toArray(arr);
                        System.out.println(arr[0]);
                        bs.sort(arr);
    this part of the bubble sort give me an error it say java.lang.null poiner exception at the[u] .compareTo & also at the top part of the code where i call fro the bs.sort(arr);// sort the array
    while (doMore) {
              n--;
         doMore =false; //assume this is our last pass
                             for (int i=0; i<n; i++) {
                                  int result = x.compareTo(x[i+1]);
                                  if (result > 0) {
                                  String temp = x;
                                  x[i] = x[i+1]; //swap
                                  x[i+1] = temp;
                                  doMore = true; // must repeat after swap

  • Need help regarding Linked List

    I'm a beginner who just spent ages working on the following code.. but need help on re-implementing the following using a linked list, i.e. no array is allowed for customer records but you still can use arrays for names, address, etc.. Hopefully I've inserted enough comments..
    Help very much appreciated!! Thanks! =]
    import java.util.Scanner;
    import java.io.*;
    public class Bank
    /* Private variables declared so that the data is only accessible to its own
         class, but not to any other class, thus preventing other classes from
         referring to the data directly */
    private static Customer[] customerList = new Customer[30];               
         //Array of 30 objects created for storing information of each customer
    private static int noOfCustomers;                                                       
         //Integer used to store number of customers in customerList
         public static void main(String[] args)
              Scanner sc = new Scanner(System.in);
              menu();
         public static void menu()
              char choice;
              String filename;
              int custId,counter=0;
              double interestRate;
    Scanner sc = new Scanner(System.in);
              do
              //Displaying of Program Menu for user to choose
         System.out.println("ABC Bank Customer Management System Menu");     
         System.out.println("========================================");
         System.out.println("(1) Input Data from File");
         System.out.println("(2) Display Data");
         System.out.println("(3) Output Data to File");
                   System.out.println("(4) Delete Record");
                   System.out.println("(5) Update Record");
         System.out.println("(Q) Quit");
                   System.out.println();
                   System.out.print("Enter your choice: ");
                   String input = sc.next();
                   System.out.println();
                   choice = input.charAt(0);     
              //switch statement used to assign each 'selection' to its 'operation'               
         switch(choice)
         case '1': int noOfRecords;
                                       System.out.print("Enter file name: ");
              sc.nextLine();                                             
              filename = sc.nextLine();
                                       System.out.println();
              noOfRecords = readFile(filename);
    System.out.println(+noOfRecords+" records read.");
              break;
         case '2': displayRecords();
              break;
         case '3': writeFile();
         break;
                        case '4': System.out.print("Enter account ID to be deleted: ");
                                       sc.nextLine();
                                       custId = sc.nextInt();
                                       deleteRecord(custId);
                                       break;
                        case '5': if(counter==0)
              System.out.print("Enter current interest rate for saving account: ");
                                            sc.nextLine();
                                            interestRate = sc.nextDouble();
                                            update(interestRate);
                                            counter++;
                                       else
              System.out.println("Error: Accounts have been updated for the month.");
                                            break;
                   }System.out.println();
         }while(choice!='Q' && choice!='q');
    /* The method readFile() loads the customer list of a Bank from a specified
         text file fileName into customerList to be stored as array of Customer
         objects in customerList in ascending alphabetical order according to the
         customer names */
    public static int readFile(String fileName)
         int custId,i=0;
              String custName,custAddress,custBirthdate,custPhone,custAccType;
              double custBalance,curRate;
              boolean d;
    /* Try block to enclose statements that might throw an exception, followed by
         the catch block to handle the exception */
    try
                   Scanner sc = new Scanner(new File(fileName));
    while(sc.hasNext())          
    /* sc.next() gets rid of "Account", "Id" and "=" */
    sc.next();sc.next();sc.next();
    custId = sc.nextInt();
                        d=checkDuplicate(custId);               
    /* checkDuplicate() is a method created to locate duplicating ids in array */
    if(d==true)
    /* A return value of true indicates duplicating record and the sc.nextLine()
         will get rid of all the following lines to read the next customer's record */
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             continue;     
    /* A return value of false indicates no duplicating record and the following
         lines containing the information of that customer's record is being read
         in */
                        if(d==false)
    /* sc.next() gets rid of "Name" and "=" and name is changed to upper case*/
         sc.next();sc.next();
         custName = sc.nextLine().toUpperCase();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of name is more than 20 characters*/
         if(custName.length()>21)
    System.out.println("Name of custId "+custId+" is more than 20 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Address" and "=" */           
         sc.next();sc.next();
         custAddress = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of address is more than 80 characters*/                         
                             if(custAddress.length()>81)
    System.out.println("Address of custId "+custId+" is more than 80 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "DOB" and "=" */                              
         sc.next();sc.next();
         custBirthdate = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of date of birth is more than 10 characters*/                         
                             if(custBirthdate.length()>11)
    System.out.println("D.O.B of custId "+custId+" is more than 10 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Phone", "Number" and "=" */                              
         sc.next();sc.next();sc.next();
         custPhone = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of phone number is more than 8 characters*/                         
                             if(custPhone.length()>9)
    System.out.println("Phone no. of custId "+custId+" is more than 8 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Account", "Balance" and "=" */                              
         sc.next();sc.next();sc.next();
         custBalance = sc.nextDouble();
    /* sc.next() gets rid of "Account", "Type" and "=" */                              
                             sc.next();sc.next();sc.next();
                             custAccType = sc.next();
                             if(custAccType.equals("Saving"))
    customerList[noOfCustomers] = new Account1(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
    sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Checking"))
    customerList[noOfCustomers] = new Account2(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Fixed"))
    sc.next();sc.next();sc.next();sc.next();
                                                 curRate = sc.nextDouble();
                                                 Account3 temp = new Account3(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType,curRate);
                                                 customerList[noOfCustomers]=temp;
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
                             else
                                  System.out.println("Account type not defined.");
         if(noOfCustomers==30)
         System.out.println("The customer list has reached its maximum limit of 30 records!");
         System.out.println();
         return noOfCustomers;
    //Exceptions to be caught
    catch (FileNotFoundException e)
    System.out.println("Error opening file");
    System.exit(0);
    catch (IOException e)
    System.out.println("IO error!");
    System.exit(0);
    /* Bubblesort method used to sort the array in ascending alphabetical order
         according to customer's name */
    bubbleSort(customerList);
              return i;
    /* The method displayRecords() displays the data of the customer records on
         screen */
    public static void displayRecords()
    int k;
    /* Displaying text using the printf() method */
         for(k=0;k<noOfCustomers;k++)
         System.out.printf("Name = %s\n", customerList[k].getName());
         System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
         System.out.printf("Account Id = %d\n", customerList[k].getId());
    System.out.printf("Address = %s\n", customerList[k].getAddress());
    System.out.printf("DOB = %s\n", customerList[k].getBirthdate());
    System.out.printf("Phone Number = %s\n", customerList[k].getPhone());
         String type = customerList[k].getAccType();
         System.out.println("Account Type = " +type);
    if(type.equals("Fixed"))
         System.out.println("Fixed daily interest = "+((Account3)customerList[k]).getFixed());
         System.out.println();               
    /* The method writeFile() saves the content from customerList into a
         specified text file. Data is printed on the screen at the same time */
    public static void writeFile()
    /* Try block to enclose statements that might throw an exception, followed by
    the catch block to handle the exception */
    try
    int i;
              int n=0;
    //PrintWriter class used to write contents of studentList to specified file
              FileWriter fwStream = new FileWriter("newCustomers.txt");
              BufferedWriter bwStream = new BufferedWriter(fwStream);
              PrintWriter pwStream = new PrintWriter(bwStream);     
    for(i=0;i<noOfCustomers;i++)
         pwStream.println("Account Id = "+customerList.getId());
              pwStream.println("Name = "+customerList[i].getName());
    pwStream.println("Address = "+customerList[i].getAddress());
    pwStream.println("DOB = "+customerList[i].getBirthdate());
    pwStream.println("Phone Number = "+customerList[i].getPhone());
              pwStream.printf("Account Balance = %.2f\n", customerList[i].getBalance());
              pwStream.println("Account Type = "+customerList[i].getAccType());
                   if(customerList[i].getAccType().equals("Fixed"))
                        pwStream.println("Fixed Daily Interest = "+((Account3)customerList[i]).getFixed());
              pwStream.println();
              n++;
    //Closure of stream
    pwStream.close();
              System.out.println(+n+" records written.");
    catch(IOException e)
    System.out.println("IO error!");     
    System.exit(0);
         //Deletes specified record from list
    public static void deleteRecord(int id)
    int i;
              i=locate(id);
    if(i==200)
    //checking if account to be deleted does not exist
    System.out.println("Error: no account with the id of "+id+" found!");
              //if account exists
    else
                        while(i<noOfCustomers)
                             customerList[i] = customerList[i+1];
                             i++;
                        System.out.println("Account Id: "+id+" has been deleted");
                        --noOfCustomers;
         //Updates the accounts
    public static void update(double interest)
    int i,j,k;
              double custBalance,addition=0;
    for(i=0;i<noOfCustomers;i++)
                        if(customerList[i] instanceof Account1)
                             for(j=0;j<30;j++)
                                  addition=customerList[i].getBalance()*interest;
                                  custBalance=customerList[i].getBalance()+addition;
                                  customerList[i].setBalance(custBalance);
                        else if(customerList[i] instanceof Account2)
                             continue;
                        else if(customerList[i] instanceof Account3)
                             for(j=0;j<30;j++)
    addition=customerList[i].getBalance()*((Account3)customerList[i]).getFixed();
    custBalance=customerList[i].getBalance()+addition;
    customerList[i].setBalance(custBalance);
                        else
                             System.out.println("Account type not defined");
              System.out.println("The updated balances are: \n");
              for(k=0;k<noOfCustomers;k++)
    System.out.printf("Name = %s\n", customerList[k].getName());
    System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
    System.out.println();
    /* ================== Additional methods ==================== */     
    /* Bubblesort method to sort the customerList in ascending alphabetical
         order according to customer's name */
    public static void bubbleSort(Customer[] x)
    int pass, index;
    Customer tempValue;      
    for(pass=0; pass<noOfCustomers-1; pass++)          
    for(index=0; index<noOfCustomers-1; index++)
    if(customerList[index].getName().compareToIgnoreCase(customerList[index+1].getName()) > 0)
    tempValue = x[index];
    x[index] = x[index+1];
    x[index+1]= tempValue;
    /* Method used to check for duplicated ids in array */     
         public static boolean checkDuplicate(int id)
              int i;
              for(i=0;i<noOfCustomers;i++)
                   if(id == customerList[i].getId())
    System.out.println("Account Id = "+id+" already exists");
                        System.out.println();
    return true;
              }return false;
    /* Method to seach for account id in array */
         public static int locate(int id)
              int j;
              for(j=0;j<noOfCustomers;j++)
                   if(customerList[j].getId()==id)
                        return j;
              j=200;
              return j;
    import java.util.Scanner;
    public class Customer
    /* The following private variables are declared so that the data is only
         accessible to its own class,but not to any other class, thus preventing
         other classes from referring to the data directly */
         protected int id;               
         protected String name,address,birthdate,phone,accType;                              
         protected double balance;               
    // Null constructor of Customer
         public Customer()
              id = 0;
              name = null;
              address = null;
              birthdate = null;
              phone = null;
              balance = 0;
              accType = null;
    /* The following statements with the keyword this activates the Customer
         (int id, String name String address, String birthdate, String phone, double
         balance) constructor that has six parameters of account id, name, address,
         date of birth, phone number, account balance and assign the values of the
         parameters to the instance variables of the object */     
         public Customer(int id, String name, String address, String birthdate, String phone, double balance, String accType)
    //this is the object reference that stores the receiver object     
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    /* The following get methods getId(), getName(), getAddress(), getBirthdate(),
         getPhone(), getBalance() return the values of the corresponding instance
         properties */     
         public int getId()
              return id;
         public String getName()
              return name;
         public String getAddress()
              return address;
         public String getBirthdate()
              return birthdate;
         public String getPhone()
              return phone;
         public double getBalance()
              return balance;
         public String getAccType()
              return accType;
    /* The following set methods setId(), setName(), setAddress(), setBirthdate(),
         setPhone and setBalance() set the values of the corresponding instance
         properties */
         public void setId (int custId)
              id = custId;
         public void setName(String custName)
              name = custName;
         public void setAddress (String custAddress)
              address = custAddress;
         public void setBirthdate (String custBirthdate)
              birthdate = custBirthdate;
         public void setPhone (String custPhone)
              phone = custPhone;
         public void setBalance (double custBalance)
              balance = custBalance;
         public void setAccType (String custAccType)
              accType = custAccType;
    class Account1 extends Customer
         public Account1(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account2 extends Customer
         public Account2(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account3 extends Customer
         protected double fixed=0;
         public Account3(int id, String name, String address, String birthdate, String phone, double balance, String accType, double fixed)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
              this.fixed = fixed;
         public double getFixed()
              return fixed;
    Example of a customers.txt
    Account Id = 123
    Name = Matt Damon
    Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
    DOB = 10-10-1970
    Phone Number = 790-3233
    Account Balance = 405600.00
    Account Type = Fixed
    Fixed Daily Interest = 0.05
    Account Id = 126
    Name = Ben Affleck
    Address = 200 Hunting Street, Singapore 784563
    DOB = 25-10-1968
    Phone Number = 432-4579
    Account Balance = 530045.00
    Account Type = Saving
    Account Id = 65
    Name = Salma Hayek
    Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
    DOB = 06-04-73
    Phone Number = 790-0000
    Account Balance = 2345.00
    Account Type = Checking
    Account Id = 78
    Name = Phua Chu Kang
    Address = 50 PCK Avenue, Singapore 639798
    DOB = 11-08-64
    Phone Number = 345-6780
    Account Balance = 0.00
    Account Type = Checking
    Account Id = 234
    Name = Zoe Tay
    Address = 100 Blue Eyed St, Singapore 456872
    DOB = 15-02-68
    Phone Number = 456-1234
    Account Balance = 600.00
    Account Type = Saving

    1) When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    2) Don't just post a huge pile of code and ask, "How do I make this work?" Ask a specific question, and post just enough code to demonstrate the problem you're having.
    3) Don't just write a huge pile of code and then test it. Write a tiny piece, test it. Then write the piece that will work with or use the first piece. Test that by itself--without the first piece. Then put the two together and test that. Only move on to the next step after the current step produces the correct results. Continue this process until you have a complete, working program.

  • Help on Linked List

    Hey people, i need a small help on my linked list.
    Ok, what i'm trying to do is have a search function with a linked list using strings. First i will have a string, i will then compute the ASCII value for that and take MOD 71 lets say. For example, a string has an ASCII value of 216, MOD 71 of this gives me 3. I will then have an array of 71, and each array will point to a linked list. There will be as many linked list as there are of arrays (71). I will then store this string at index [3] in the linked list in which the array points to.
    My problem for now is, how do i for example create 71 linked list? So far i can create only 1. To create another is easy, but if i have 71 the code will be too much. Is there an iterator i could use that easily creates 71? Sorry about this, i'm not really good with linked list with Java. Anyway, here is what i have now :).
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public static MyLinkedListElement head;
        public MyLinkedList() {   
            head = null;
       public static void addToHead(String s) {
            MyLinkedListElement a = new MyLinkedListElement(s);
            if (head == null) {
                head = a;
            } else {
                a.next = head;
                head = a;       
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              for (int i = 0; i < arr.length; i++) {
                          addToHead(arr);
    MyLinkedListElement current = head;
    while (current != null) {
    System.out.println(current.getValue());
    current = current.next;
    }I can have an array of strings and easily add them to a linked list.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I am very confused now, i just need to store a string value inside an array of linked list. But i can't somehow do it. I am very close, i can store the value in a linked list but the array of linked list, this is what i have.
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public MyLinkedListElement head;
        public MyLinkedList() {   
              head = null;
        public void addToHead(String s) {
             MyLinkedListElement  a = new MyLinkedListElement(s);
             MyLinkedList[] arrayOfLinkedLists = new MyLinkedList[71];
             for(int i = 0; i < arrayOfLinkedLists.length; i++) {
                 arrayOfLinkedLists[i] = new MyLinkedList();
             if (head == null) {    
                 head = a;
             } else {
                 a.next = head;
                 head = a;       
        public void print(MyLinkedListElement current) {
              while (current  != null) {
                    System.out.println(current.getValue());
                    current = current.next;
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              MyLinkedList listInstance = new MyLinkedList();
              for (int i = 0; i < arr.length; i++) {
                    listInstance.addToHead(arr);
    MyLinkedListElement current = listInstance.head;
    listInstance.print(current);

  • Linked list- error problem.... HELP!!!

    Just got to the point that i'm better at drinking java than programing java....
    how ever... I have done person register with Linked list. There are like 4 options:
    1. New post
    2. search
    3. search and change
    4. remove post
    U can enter your name, adress and personal code number while making a new post, but when I've removed it ( l.list.remove(p);)and then search for it I get the error message "Exception in thread "main"....bla bla..". Why? and how do I get around this prob? PLEASE HELP ME!! gotta hand this in tonight!
    Thank U!!
    //Phil

    Phil,
    LinkedList itself works as advertised (1.3.1). For example:
    LL = LinkedList()
    LL.add("apple")
    LL.add("battle")
    LL.add("cattle")
    // printing LL yields all 3
    LL.remove("battle")
    // printing LL yields apple, cattle
    You may need to post for responders to get a better idea. If posting code please enclose in  blocks so it's formatted properly.
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can someone help with splitting a Linked List.??

    Any help would be awesome!!!
    My code just will not work!! Any help would be appreciated! My problem is in the last method SplitAt. These are the conditions set and my code:
    Splitting a Linked List at a Given Node, into Two Sublists
    a. Add the following as an abstract method to the class
    LinkedListClass:
    public void splitAt (LinkedListClass<T> secondList, T item);
    //This method splits the list at the node with the info item into two sublists.
    //Precondition: The list must exist.
    //Postcondition: first and last point to the first and last nodes of the first sublist,
    // respectively. secondList.first and secondList.last point to the first
    // and last nodes of the second sublist.
    Consider the following statements:
    UnorderedLinkedList<Integer> myList;
    UnorderedLinkedList<Integer> otherList;
    Suppose myList points to the list with the elements 34, 65, 18, 39, 27, 89, and 12 (in this order). The statement
    myList.splitAt(otherList, 18);
    splits myList into two sublists: myList points to the list with elements 34 and 65, and otherList points to the sublist with elements 18, 39, 27, 89, and 12.
    b. Provide the definition of the method splitAt in the class UnorderedLinkedList. Also write a program to test your method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
           //Default constructor
        public UnorderedLinkedList()
            super();
            //Method to determine whether searchItem is in
            //the list.
            //Postcondition: Returns true if searchItem is found
            //               in the list; false otherwise.
        public boolean search(T searchItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            boolean found;
            current = first;  //set current to point to the first
                              //node in the list
            found = false;    //set found to false
            while (current != null && !found) //search the list
                if (current.info.equals(searchItem)) //item is found
                    found = true;
                else
                   current = current.link; //make current point to
                                           //the next node
            return found;
            //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(T newItem)
            LinkedListNode<T> newNode;     //variable to create the
                                        //new node
            newNode =
               new LinkedListNode<T>(newItem, first); //create and
                                           //insert newNode before
                                           //first
            first = newNode;   //make first point to the
                               //actual first node
            if (last == null)   //if the list was empty, newNode is
                                //also the last node in the list
                last = newNode;
            count++;     //increment count
            //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //               newItem is inserted at the end
            //               of the list. Also, last points to
            //               the last node and
            //               count is incremented by 1.
        public void insertLast(T newItem)
            LinkedListNode newNode; //variable to create the
                                    //new node
            newNode =
               new LinkedListNode(newItem, null);  //create newNode
            if (first == null)  //if the list is empty, newNode is
                                //both the first and last node
                first = newNode;
                last = newNode;
            else     //if the list is not empty, insert
                     //newNode after last
                last.link = newNode; //insert newNode after last
                last = newNode;      //set last to point to the
                                     //actual last node
            count++;
        }//end insertLast
            //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //               deleteItem is deleted from the
            //               list. Also, first points to the first
            //               node, last points to the last
            //               node of the updated list, and count
            //               is decremented by 1.
        public void deleteNode(T deleteItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            LinkedListNode<T> trailCurrent; //variable just
                                            //before current
            boolean found;
            if ( first == null)    //Case 1; the list is empty
                System.err.println("Cannot delete from an empty "
                                 + "list.");
            else
                if (first.info.equals(deleteItem)) //Case 2
                    first = first.link;
                       if (first == null)  //the list had only one node
                          last = null;
                       count--;
                else  //search the list for the given info
                    found = false;
                    trailCurrent = first; //set trailCurrent to
                                          //point to the first node
                    current = first.link; //set current to point to
                                          //the second node
                    while (current != null && !found)
                        if (current.info.equals(deleteItem))
                            found = true;
                        else
                            trailCurrent = current;
                            current = current.link;
                    }//end while
                    if (found) //Case 3; if found, delete the node
                        count--;
                        trailCurrent.link = current.link;
                        if (last == current)  //node to be deleted
                                              //was the last node
                           last = trailCurrent;  //update the value
                                                 //of last
                    else
                       System.out.println("Item to be deleted is "
                                        + "not in the list.");
                }//end else
            }//end else
        }//end deleteNode
        public void splitAt(LinkedListClass<T> secondList, T item)
         LinkedListNode<T> current;
         LinkedListNode<T> trailCurrent;
         int i;
         boolean found;
         if (first==null)
        System.out.println("Empty.");
        first=null;
        last=null;
        count--;
         else
              current=first;
              found=false;
              i=1;
              while(current !=null &&!found)
                   if(current.info.equals(secondList))
                       found= true;
                       else
                            trailCurrent=current;
                            i++;
              if(found)
                   if(first==current)
                        first=first;
                        last=last;
                        count=count;
                        count=0;
                   else
                        first=current;
                        last=last;
                        last=null;
                        count = count- i+1;
                        count = i-1;
                   else
                        System.out.println("Item to be split at is "
                             + "not in the list.");
                   first=null;
                   last=null;
                   count=0;
        }Edited by: romeAbides on Oct 10, 2008 1:24 PM

    I dont have a test program at all. The program is supposed to prompt for user input of numbers. (it does) Take the input and end at input of -999 (it does). Then it asks user where it wants to split list (it does). When I enter a number it does nothing after that. I am going to post updated code and see if that helps along with all the classes. Thanks!
    This is the class to prompt:
    import java.util.*;
    public class Ch16_ProgEx6
        static Scanner console = new Scanner(System.in);
         public static void main(String[] args)
             UnorderedLinkedList<Integer> list
                              = new UnorderedLinkedList<Integer>();
            UnorderedLinkedList<Integer> subList =
                              new UnorderedLinkedList<Integer>();
             Integer num;
             System.out.println("Enter integers ending with -999.");
             num = console.nextInt();
             while (num != -999)
                 list.insertLast(num);
                 num = console.nextInt();
            System.out.println();
            System.out.println("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("Enter the number at which to split list: ");
            num = console.nextInt();
            list.splitAt(subList, num);
            System.out.println("Lists after splitting list");
            System.out.print("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("sublist: ");
            subList.print();
            System.out.println();
            System.out.println("Length of sublist: " + subList.length());
    }This is the ADT:
    public interface LinkedListADT<T> extends Cloneable
        public Object clone();
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public boolean isEmptyList();
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public void initializeList();
           //Method to initialize the list to an empty state.
           //Postcondition: The list is initialized to an empty
           //               state.
        public void print();
           //Method to output the data contained in each node.
        public int length();
           //Method to return the number of nodes in the list.
           //Postcondition: The number of nodes in the list is
           //               returned.
        public T front();
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T back();
           //Method to return a reference of object containing
           //the data of the last node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the last node
           //               is returned.
        public boolean search(T searchItem);
           //Method to determine whether searchItem is in the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public void insertFirst(T newItem);
           //Method to insert newItem in the list.
           //Postcondition: newItem is inserted at the
           //               beginning of the list.
        public void insertLast(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: newItem is inserted at the end
           //               of the list.
        public void deleteNode(T deleteItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list.
        public void splitAt(LinkedListClass<T> secondList, T item);
    }This is the linked list class:
    import java.util.NoSuchElementException;
    public abstract class LinkedListClass<T> implements LinkedListADT<T>
        protected class LinkedListNode<T> implements Cloneable
            public T info;
            public LinkedListNode<T> link;
               //Default constructor
               //Postcondition: info = null; link = null;
            public LinkedListNode()
                info = null;
                link = null;
               //Constructor with parameters
               //This method sets info pointing to the object to
               //which elem points to and link is set to point to
               //the object to which ptr points to.
               //Postcondition:  info = elem; link = ptr;
            public LinkedListNode(T elem, LinkedListNode<T> ptr)
                info = elem;
                link = ptr;
               //Returns a copy of objects data in store.
               //This method clones only the references stored in
               //the node. The objects that the nodes point to
               //are not cloned.
            public Object clone()
                LinkedListNode<T> copy = null;
                try
                    copy = (LinkedListNode<T>) super.clone();
                catch (CloneNotSupportedException e)
                    return null;
                return copy;
               //Method to return the info as a string.
               //Postcondition: info as a String object is
               //               returned.
            public String toString()
                return info.toString();
        } //end class LinkedListNode
        public class LinkedListIterator<T>
            protected LinkedListNode<T> current;  //variable to
                                                  //point to the
                                                  //current node in
                                                  //list
            protected LinkedListNode<T> previous; //variable to
                                                  //point to the
                                                  //node before the
                                                  //current node
               //Default constructor
               //Sets current to point to the first node in the
               //list and sets previous to null.
               //Postcondition: current = first; previous = null;
            public LinkedListIterator()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to reset the iterator to the first node
               //in the list.
               //Postcondition: current = first; previous = null;
            public void reset()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to return a reference of the info of the
               //current node in the list and to advance iterator
               //to the next node.
               //Postcondition: previous = current;
               //               current = current.link;
               //               A refrence of the current node
               //               is returned.
            public T next()
                if (!hasNext())
                    throw new NoSuchElementException();
                LinkedListNode<T> temp = current;
                previous = current;
                current = current.link;
                return temp.info;
                //Method to determine whether there is a next
                //element in the list.
                //Postcondition: Returns true if there is a next
                //               node in the list; otherwise
                //               returns false.
            public boolean hasNext()
                return (current != null);
               //Method to remove the node currently pointed to
               //by the iterator.
               //Postcondition: If iterator is not null, then the
               //               node that the iterator points to
               //               is removed. Otherwise the method
               //               throws NoSuchElementException.
            public void remove()
                if (current == null)
                    throw new NoSuchElementException();
                if (current == first)
                    first = first.link;
                    current = (LinkedListNode<T>) first;
                    previous = null;
                    if (first == null)
                        last = null;
                else
                    previous.link = current.link;
                    if (current == last)
                        last = first;
                        while (last.link != null)
                            last = last.link;
                    current = current.link;
                count--;
               //Method to return the info as a string.
               //Postcondition: info as a String object is returned.
            public String toString()
                return current.info.toString();
        } //end class LinkedListIterator
           //Instance variables of the class LinkedListClass
        protected LinkedListNode<T> first; //variable to store the
                                           //address of the first
                                           //node of the list
        protected LinkedListNode<T> last;  //variable to store the
                                           //address of the last
                                           //node of the list
        protected int count;  //variable to store the number of
                              //nodes in the list
           //Default constructor
           //Initializes the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public LinkedListClass()
            first = null;
            last = null;
            count = 0;
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public boolean isEmptyList()
            return (first == null);
           //Method to initialize the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public void initializeList()
            first = null;
            last = null;
            count = 0;
           //Method to output the data contained in each node.
        public void print()
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            current = first;    //set current so that it points to
                                //the first node
            while (current != null) //while more data to print
                System.out.print(current.info + " ");
                current = current.link;
        }//end print
           //Method to return the number of nodes in the list.
           //Postcondition: The value of count is returned.
        public int length()
            return count;
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T front()
            return first.info;
            //Method to return a reference of object containing
            //the data of the last node of the list.
            //Precondition: The list must exist and must not be empty.
            //Postcondition: The reference of the object that
            //               contains the info of the last node
            //               is returned.
        public T back()
            return last.info;
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public Object clone()
            LinkedListClass<T> copy = null;
            try
                copy = (LinkedListClass<T>) super.clone();
            catch (CloneNotSupportedException e)
                return null;
                //If the list is not empty clone each node of
                //the list.
            if (first != null)
                   //Clone the first node
                copy.first = (LinkedListNode<T>) first.clone();
                copy.last = copy.first;
                LinkedListNode<T> current;
                if (first != null)
                    current = first.link;
                else
                    current = null;
                   //Clone the remaining nodes of the list
                while (current != null)
                    copy.last.link =
                            (LinkedListNode<T>) current.clone();
                    copy.last = copy.last.link;
                    current = current.link;
            return copy;
           //Method to return an iterator of the list.
           //Postcondition: An iterator is instantiated and
           //               returned.
        public LinkedListIterator<T> iterator()
            return new LinkedListIterator<T>();
           //Method to determine whether searchItem is in
           //the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public abstract boolean search(T searchItem);
           //Method to insert newItem in the list.
           //Postcondition: first points to the new list
           //               and newItem is inserted at the
           //               beginning of the list. Also,
           //               last points to the last node and
           //               count is incremented by 1.
        public abstract void insertFirst(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: first points to the new list and
           //               newItem is inserted at the end
           //               of the list. Also, last points to
           //               the last node and
           //               count is incremented by 1.
        public abstract void insertLast(T newItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list. Also, first points to the first
           //               node, last points to the last
           //               node of the updated list, and count
           //               is decremented by 1.
        public abstract void deleteNode(T deleteItem);
        public abstract void splitAt(LinkedListClass<T> secondList, T item);
    }And this is the UnorderedLinked Class with the very last method the one being Im stuck on. The SplitAt Method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
           //Default constructor
        public UnorderedLinkedList()
            super();
            //Method to determine whether searchItem is in
            //the list.
            //Postcondition: Returns true if searchItem is found
            //               in the list; false otherwise.
        public boolean search(T searchItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            boolean found;
            current = first;  //set current to point to the first
                              //node in the list
            found = false;    //set found to false
            while (current != null && !found) //search the list
                if (current.info.equals(searchItem)) //item is found
                    found = true;
                else
                   current = current.link; //make current point to
                                           //the next node
            return found;
            //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(T newItem)
            LinkedListNode<T> newNode;     //variable to create the
                                        //new node
            newNode =
               new LinkedListNode<T>(newItem, first); //create and
                                           //insert newNode before
                                           //first
            first = newNode;   //make first point to the
                               //actual first node
            if (last == null)   //if the list was empty, newNode is
                                //also the last node in the list
                last = newNode;
            count++;     //increment count
            //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //               newItem is inserted at the end
            //               of the list. Also, last points to
            //               the last node and
            //               count is incremented by 1.
        public void insertLast(T newItem)
            LinkedListNode newNode; //variable to create the
                                    //new node
            newNode =
               new LinkedListNode(newItem, null);  //create newNode
            if (first == null)  //if the list is empty, newNode is
                                //both the first and last node
                first = newNode;
                last = newNode;
            else     //if the list is not empty, insert
                     //newNode after last
                last.link = newNode; //insert newNode after last
                last = newNode;      //set last to point to the
                                     //actual last node
            count++;
        }//end insertLast
            //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //               deleteItem is deleted from the
            //               list. Also, first points to the first
            //               node, last points to the last
            //               node of the updated list, and count
            //               is decremented by 1.
        public void deleteNode(T deleteItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            LinkedListNode<T> trailCurrent; //variable just
                                            //before current
            boolean found;
            if ( first == null)    //Case 1; the list is empty
                System.err.println("Cannot delete from an empty "
                                 + "list.");
            else
                if (first.info.equals(deleteItem)) //Case 2
                    first = first.link;
                       if (first == null)  //the list had only one node
                          last = null;
                       count--;
                else  //search the list for the given info
                    found = false;
                    trailCurrent = first; //set trailCurrent to
                                          //point to the first node
                    current = first.link; //set current to point to
                                          //the second node
                    while (current != null && !found)
                        if (current.info.equals(deleteItem))
                            found = true;
                        else
                            trailCurrent = current;
                            current = current.link;
                    }//end while
                    if (found) //Case 3; if found, delete the node
                        count--;
                        trailCurrent.link = current.link;
                        if (last == current)  //node to be deleted
                                              //was the last node
                           last = trailCurrent;  //update the value
                                                 //of last
                    else
                       System.out.println("Item to be deleted is "
                                        + "not in the list.");
                }//end else
            }//end else
        }//end deleteNode
        public void splitAt(LinkedListClass<T> secondList, T item)
         LinkedListNode<T> current;
         LinkedListNode<T> trailCurrent;
         int i;
         boolean found;
         if (first==null)
        System.out.println("Empty.");
        first=null;
        last=null;
        count--;
        count=0;
         else
              current=first;
              found=false;
              i=1;
              while(current !=null &&!found)
                   if(current.info.equals(item))
                       found= true;
                       else
                            trailCurrent=first;
                            current=first;
                            i++;
              if(found)
                   if(first==current)
                        first.link=first;
                        last.link=last;
                           count--;
                        count=0;
                   else
                        first.link=current;
                        last.link=last;
                        last=null;
                        count = count- i+1;
                        count = i-1;
              } else  {
                  System.out.println("Item to be split at is "
                    + "not in the list.");
                   first=null;
                   last=null;
                   count=0;
        Any help or just advice would be fine. Im not the best at Java, better at VB. Am completely stumped! Thanks so much!

  • New to java  -especially linked lists

    I�m trying to work with linked lists but not having much luck�
    Overall, the program must create a datastructure that will hold titles of articles. Up to 10 keywords can be added to each article and it must then be possible to search all of the titles for matches to the keyword.
    Currently I�m stuck in a for-loop � my linked list (articleList) is not accepted. Any help would be much appreciated. The following error occurs when I attempt to compile:
    SearchMachine.java:30: cannot resolve symbol
    symbol : variable articleList
    location: class SearchMachine
              for(ListIterator listiter = articleList.listIterator(); listiter.hasNext();)
    ^
    import java.util.*;
    class Document
         private String title;
         private String keywords [] = new String [10];
         private int last = 0;
         public Document (String _title)
              String title = _title;
         public void addKeyword(String kw)
              if(last < 9)
                   keywords [last]= kw;
                   last ++;
                   System.out.println("The keyword " + kw + " has now been added");
              else if (last == 9)
                   keywords [last]= kw;
                   System.out.println ("The document now has 10 keywords. No more can be added");
    class SearchMachine
         SearchMachine()
              LinkedList articleList = new LinkedList ();
              articleList.add (new Document ("Oracle 8 the new SQL programming"));
              articleList.add (new Document ("Java programming made easy"));
         public void print()
              for(ListIterator listiter = articleList.listIterator(); listiter.hasNext();)
                   System.out.println(listiter.next());
         public static void main (String [] args)
              SearchMachine search;     
              search = new SearchMachine();
              search.print();

    This is a basic scope issue. You declare the variable articleList inside the constructor block and thus it's visible only in the constructor block. The variable doesn't exist anywhere else but in SearchMachine() {...} The solution is to move the line "LinkedList articleList = new LinkedList();" three lines up, outside the constructor but inside the class definition, so that articleList becomes a member of the SearchMachine class.

Maybe you are looking for