Replace node in a linked list.

Hello everyone,
Im trying to replace a node with the following method :
@Override
     public boolean replace(Object oneThing) {
          Node aNode = find(oneThing); // gets a node previous to oneThing
          if(aNode == null)
               return false;
          oneThing = aNode.next.next;
          aNode.next = (Node) ((Copyable) oneThing).copy();
          return true;
     }I keep getting this error and dont know how to fix it or what im doing wrong:
Exception in thread "main" java.lang.ClassCastException: myContainers.List$Node cannot be cast to myUtils.CopyableAny help is greatly appreciated.

Nevermind I got It! thanks

Similar Messages

  • Replacing nodes in a linked list

    Hello there, i was having problems replacing all nodes of a specific value to another value, andi have no idea what i was doing wrong. this is what i had:     public void replace(int oldVal, int newVal) {
             IntNode traveller = front;
             if (traveller == null){
                  System.out.println("No list exists");
             } else {         
                  while (traveller != null){
                       if (traveller == oldVal) {
                            traveller = newVal;
                       traveller = traveller.next;
        }I seem to be getting some kind of syntax error on "if (traveller == oldVal) " and another error on "traveller = newVal;"
    Any idea on what I'm doing wrong?

    vexity wrote:
    well i didn't run the program Yeah, I know, because you have syntax errors. You can get descriptive messages for those sytax errors that you can copy and paste here.
         Incompatible operand types IntList.IntNode and int
         Type mismatch: cannot convert from int to IntList.IntNode
         at IntList.replace(IntList.java:157)
         at IntListTest.dispatch(IntListTest.java:84)
         at IntListTest.main(IntListTest.java:25)
    Yeah, like that. That's what we want to see.
    But as I already told you, the problem is that you're trying to mix ints and IntNodes.
    What should i do to solve this problem?Use ints where appropriae, IntNodes where appropriate, and convert between the two when you need to. You do know how to create an IntNode from an int, and how to get an int out of an IntNode, right?

  • Recursively Finding a Node in a Linked List

    I'm trying to find a node recursively in this linked list but keep coming up with an error message - can anyone tell me what is wrong?
         public boolean find (Object obj)
              DonorNode node = new DonorNode(obj);
              DonorNode current = list;
              if (don.equals(current))
                   return true;
              else
                   return find(current.next);
         }

    Please post within code tags (button above the message box).
    Without more information it's hard to say.
    What is list?
    What is don?
    If you don't mind me pointing out:
    A method named find conventionally returns some object it is searching for or null if not found.
    What you have (by that I mean a method returning boolean) is generally named contains (or some other obvious predicate name).
    That being said, if I assume that DonorNodes contain some Object and have getter functions to access those; and that list is a DonorNode representing the head of the list, try something like:public boolean contains(Object o) {
        return contains(o, list);
    private boolean contains(Object o, DonorNode n) {
        if (n.getObject() == o)
            return true;
        if (n.getNext() == null)
            return false;
        return contains(o, n.getNext());
    }Although keep in mind that comparing two Objects using '==' will result in reference only comparison. If you need some other form of comparison you might consider using the equals method (make sure you then implement it in all potentially contained classes) or even narrowing the accepted argument to classes that implement the Comparable interface.
    Hope this helps.

  • Recursion using a linked list

    I am confused at how to make a linked list using recursion. I've been looking at the syntax and examples from the web for the past couple hours, but all seem to be based on an empty .java file. I need to put it in my code somehow. here's the code segment:
    public static boolean RecursiveTest (String s, int start, Node n) {
    // The linked list
    Node<char> bracket = new Node<char>();
    int size = s.length();
    char v = s.charAt(start);
    //String sElement = parens.top();
    boolean isGood = true;
    // ending "ifs"
    if (size == 0) { System.out.println("empty string");  return false; }
    if (start == size) return isGood;
    if (s.charAt(start) == '(' || s.charAt(start) == '[' ||
              s.charAt(start)== '{') {
    v.Push(sChar);
    System.out.println(sChar);
    return RecursiveTest(start+1, s.charAt(start));
    else if (sChar.equals(")") && sElement.equals("(")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("]") && sElement.equals("[")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("}") && sElement.equals("{")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals(")") && !sElement.equals("(")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("]") && !sElement.equals("[")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("}") && !sElement.equals("{")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else return RecursiveTest(start+1);
    } // end of RecursiveTest
    I'm passing a string, 0, and a new node (i dunno about the last one there), from an above main class.
    This code is wrong, i know, but it's all I got done so far. How would I be able to make a linked list inside this method?

    No one knows how to do a linked list inside a recursive method?Yes we do, but you have to realize that a list (whether it be a linked list
    or an array list or whatever) has nothing to do with recursion per se.
    If that list has to keep track of some state it certainly mustn't be created
    within that recursive method as a local variable. And (see my previous
    reply), what do you need recursion for? Counting and pairing brackets
    can easily be done using an iterative method where the list keeps track
    of the last seen left bracket (of any type).
    kind regards,
    Jos

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

  • Putting a class of objects in a Linked List?

    Hi,
    I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class studentRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected Object datum;
              protected Node link;
              public Node() {}
              public Node(Object item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(Object datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
    Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
    Thanks in advance.

    Hi jverd,
    Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class sRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected sRecord datum;
              protected Node link;
              public Node() {}
              public Node(sRecord item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(sRecord datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
         //method to delete an object from the linked list
         public boolean delete(Object scrap)
              Node previous = head;
              //for every node in the linked list
              for (Node current = head; current != null; current = current.link)
                   //node to be deleted is at the head of the list
                   if (current.datum.equals(scrap) && previous == current)
                        head = current.link;
                        if (head == null) tail = null;
                        nodeCount--;
                        return true;
                   //node to be deleted is after the first node and before the last
                   else if (current.datum.equals(scrap) && (current.link != null))
                        previous.link = current.link;
                        nodeCount--;
                        return true;
                   //node to be deleted is at the ned of list
                   else if (current.datum.equals(scrap) && (current.link == null))
                        tail = previous;
                        previous.link = null;
                        nodeCount--;
                        return true;
                   previous = current;
              return false;
         //method to display the contents of a linked list
         public void displayList()
              Node temporary = head;
              if (head == null)
                   IO.screen.println("linked list is empty");
                   return;
              while (temporary != null)
                   IO.screen.println(temporary.datum);
                   temporary = temporary.link;
         //method to return true if the linked list is empty
         public boolean isEmpty()
              return (nodeCount == 0);
         //method to return the number of nodes in the linked list
         public int nodes()
              return nodeCount;
         //method to display a menu to insert data into the linked list
         static private char menu()
              char response = '\u0000';
              IO.screen.println("Do you want to ");
              IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
              IO.screen.flush();
              boolean done=false;
              do
                   try
                        String data = IO.keyboard.readLine();
                        response = Character.toUpperCase(data.charAt(0));
                        done = true;
                   catch (Exception e)
                        IO.screen.println("Please input a single character I, D, L or E");
              } while (! done);
              return response;
         static public void main(String[] args) throws IOException
              LinkedList list = new LinkedList();
              String datum;
              char choice;
              //get information from menu
              choice = menu();
              for (;;)
                   //Menu
                   switch (choice)
                        case 'I' :
                             IO.screen.println("type quit to finish input");
                             IO.screen.print("Enter a word ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                             while (! datum.equals("quit"))
    THE ERROR HAPPENS HERE ON THIS LINE          list.insert(datum.name);
                                  IO.screen.print("Enter another word");
                                  IO.screen.flush();
                                  datum = IO.keyboard.readLine();
                             break;
                   case 'D' :
                        //if list is empty deletion not possible
                        if (list.isEmpty())
                             IO.screen.println("linked list is empty");
                             break;
                        IO.screen.println("type quit to finish input");
                        IO.screen.print("Delete? ");
                        IO.screen.flush();
                        datum = IO.keyboard.readLine();
                        while (! datum.equals("quit"))
                             if (list.delete(datum))
                                  IO.screen.println(datum+" was scrapped!");
                             //if list is empty deletion is not possible
                             if (list.isEmpty())
                                  IO.screen.println("linked list is empty");
                                  break;
                             IO.screen.print("Delete? ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                        break;
                   case 'L' :
                        list.displayList();
                        IO.screen.println("number of nodes " + list.nodes());
                        break;
                   case 'E' : System.exit(0);
              //get information from menu
              choice = menu();

  • Linked List trouble

    //I need to add a header node into this Linked list class and
    // i dont understand it. can anyone give me a few pointers.
    // This is the orginal code. What im trying to figure out is below.
    public abstract class LinkedList implements ListInterface
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;
    public boolean isFull()
    // Determines whether this list is full.
    return false;
    public int lengthIs()
    // Determines the number of elements on this list.
    return numItems;
    public abstract boolean isThere (Listable item);
    // Determines if element matching item is on this list.
    public Listable retrieve (Listable item)
    // Returns a copy of the list element with the same key as item.
    ListNode location = list;
    boolean found = false;
    while (!found)
    if (item.compareTo(location.info) == 0) // if they match
    found = true;
    else
    location = location.next;
    return location.info.copy();
    public abstract void insert (Listable item);
    // Adds a copy of item to this list.
    public void delete (Listable item)
    // Deletes the element of this list whose key matches item�s key.
    ListNode location = list;
    // Locate node to be deleted.
    if (item.compareTo(location.info) == 0)
    list = list.next; // Delete first node.
    else
    while (item.compareTo(location.next.info) != 0)
    location = location.next;
    // Delete node at location.next.
    location.next = location.next.next;
    numItems--;
    public void reset()
    // Initializes current position for an iteration through this list.
    currentPos = list;
    public Listable getNextItem ()
    // Returns copy of the next element in list.
    Listable nextItemInfo = currentPos.info.copy();
    if (currentPos.next == null)
    currentPos = list;
    else
    currentPos = currentPos.next;
    return nextItemInfo;
    //now heres the part i dont get i need to make list point to a new
    // node say HeaderNode. Now wouldnt just...
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list.next = HeaderNode; //....this line do the trick???
    currentPos = null;
    I know that i cant use any insert methods to put it in, so what else could i possibly do?

    bump

  • Implementing my own linked lists...aiiieee!

    Hi,
    I'm trying to implement my own linked list structure oftype String. It will eventually go to form a simple text editor, with each line of a file being loaded into its own String node.
    However, im having problems implementing the list itself :)
    So far ive got the file to read in succesfully, but now im stuck...how do i load up a line into a new node? and what about the head/tail nodes, they just confuse me! Do i have to write a seperate 'List' class and create an object of that, much like the LinkedList class with Java?
    Any help or a nudge in the right direction would be appreciated,
    TIA
    andrew
    PS code below ...
    =================================
    =================================
    import java.io.*;
    import java.util.*;
    class Editor {
    public static void main(String[] args) {
    ///LOAD UP THE TEXT FILE//////////////////////////////////////
         String file = "s.txt";
         String line;
         System.out.println(System.in);
         //testing here...
    StringNode alist = new StringNode(null,null);
         try{
              FileReader FR = new FileReader(file);
              BufferedReader BR = new BufferedReader(FR);
              while ( (line = BR.readLine()) != null ){
                   alist.addNodeAfter(line);
                   System.out.println(line);
                   }//while
         }//try
         catch(IOException e){
              System.out.println(file + " not found");
         }//catch
    ///COMMANDS///////////////////////////////////////////////////
    //text editor commands to be input via command line type console. how to grab inputs on return?
    }//main
    }//Editor
    //code to create a node...but now what?
         class StringNode
         private String data;
         private StringNode link;
         // constructor for initialisation
         public StringNode(String initialData, StringNode initialLink)
              data = initialData;
              link = initialLink;
         // accessor method to get the data from this node
         public String getData( )
              return data;
         // accessor method to get a reference to the next node after this node.
         public StringNode getLink( )
              return link;
         // modification method to set the data in this node.
         public void setData(String newData)
              data = newData;
         // modification method to set the link to the next node after this node
         public void setLink(StringNode newLink)
              link = newLink;
         // add a new node after this node
         public void addNodeAfter(String item)
              link = new StringNode(item, link);
         // modification method to remove the node after this node.
         public void removeNodeAfter( )
              link = link.link;
         // compute the number of nodes in a linked list
         public static int listLength(StringNode head)
              StringNode cursor;
              int answer;
              answer = 0;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   answer++;
              return answer;
         // print the nodes in a linked list
         public static void listPrint(StringNode head)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData());
         // print the nodes in a linked list skipping dummy node at head
         public static void listPrint2(StringNode head)
              StringNode cursor;
              for (cursor = head.link; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData()+" ");
         // search for a particular piece of data in a linked list
         public static StringNode listSearch(StringNode head, String target)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   if (target == cursor.data)
                        return cursor;
              return null;
    }

    You wouldn't by any chance be doing computer science at Cardiff university would you and have been given this as an assignment?

  • Implementation of Linked List class

    I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.

    Here is an example of a linked list. Hope that will help.
    // define a node of a linked list
    public class Node
    public int data; // point to data
    public Node next; // pointer to next node or point to null if end of list
    // listTest1
    public class ListTest1
    public static void main(String[] args)
    Node list;
    list = new Node();
    list.data = 3;
    list.next = new Node();
    list.next.data = 7;
    list.next.next = new Node();
    list.next.next.data = 12;
    list.next.next.next = null;
    Node current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();
    // other listnode
    public class ListNode
    public int data;
    public ListNode next;
    public ListNode()
    // post: constructs a node with data 0 and null link
    this(0, null);
    public ListNode(int value)
    // post: constructs a node with given data and null link
    this(value, null);
    public ListNode(int value, ListNode link)
    // post: constructs a node with given data and given link
    data = value;
    next = link;
    Contents of ListTest2.java
    public class ListTest2
    public static void main(String[] args)
    ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
    ListNode current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();

  • 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

  • Appending in linked list

    Hello there, my question is regarding linked lists.
    I'm not sure why but I have some confusion about 'append' or rather the definition of it
    is appending a node to a linked list the same as adding a node to the end of the linked list?
    If so would it be possible to do this by making a new node (ie. newNode) and making tail = newNode ?

    vexity wrote:
    do i do a tail.next = newNode and then tail = newNode ?Try it and see what happens.

  • Linked list troubles

    How do i put a headernode into this constructor?
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;

    You mean...
    public LinkedList(ListNode nodeHeader)
      numItems = 0;
      list = nodeHeader;
      currentPos = null;

  • Splitting a Linked List at a Given Node, into Two Sublists??

    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;
    }

    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!

  • Linked List  - deleeting nodes - HELP!

    How do I delete all occurences of the nodes with the same parameters in the linked list ?
    example:
    Node1-> Node2 ->Node3->Node4->Node5
    Node1, Node4, and Node5 have the same String value, how do I delete them in one method without breaking the linked list ?
    thanks

    Hi,
    You have iterate thru the linked list remove one by one. Also have look at other collection classes like HashSet or HashMap for fast retrieval.

  • Linked lists - changing nodes

    Hello,
    I have a double linked list where I want to change one node to another and change its references at the same time.
    The nodes are not together i.e. they do not appear in the list consectutively.
    I need to swap like B and D - I have managed to do swaps like A and B, and C and D (that took a while).
    Is this logic correct (I am using temporary nodes):
    if(f1 != (f2 - 1))
         Object temp = object1;
         Object temp2 = object2;
         object1.getPrevious().setNext(object2);
         object2.getNext().setPrevious(object1);
         object1.getNext().setPrevious(object2);
         object2.getPrevious().setNext(object1);
         object1.setPrevious(temp2.getPrevious());
         object1.setNext(temp2.getNext());
         object2.setPrevious(temp.getPrevious());
         object2.setNext(temp.getNext());
    If this logic is not correct then please only give hints as to why.
    Cheers

    Hello,
    I have a double linked list where I want to change
    one node to another and change its references at the
    same time.
    The nodes are not together i.e. they do not appear in
    the list consectutively.
    I need to swap like B and D - I have managed to do
    swaps like A and B, and C and D (that took a while).
    Is this logic correct (I am using temporary nodes):
    if(f1 != (f2 - 1))
         Object temp = object1;
         Object temp2 = object2;
         object1.getPrevious().setNext(object2);
         object2.getNext().setPrevious(object1);
         object1.getNext().setPrevious(object2);
         object2.getPrevious().setNext(object1);
         object1.setPrevious(temp2.getPrevious());
         object1.setNext(temp2.getNext());
         object2.setPrevious(temp.getPrevious());
         object2.setNext(temp.getNext());
    If this logic is not correct then please only give
    hints as to why.
    CheersI didn't check your logic, but I think that there are errors in it since I saw these lines:
    object1.setPrevious(temp2.getPrevious());
    object1.setNext(temp2.getNext());
    object2.setPrevious(temp.getPrevious());
    object2.setNext(temp.getNext()); temp and temp2 are not copies of object1 and object2. They are references to the same object, so when you do e.g. object1.getPrevious().setNext() you also change previous->next for temp.
    temp == object1
    temp2 == object2
    Kaj

Maybe you are looking for

  • Spilled soda on laptop--right/left click not working

    My 2 year old spilled soda on my HP G60 laptop last night. I immediately turn off computer and turned it upside down and cleaned it up. I booted up fine later on. Everything seemed fine until I realized my right/left click was not working. I can navi

  • How can I tell if I have 3G or 3GS iPhone?

    I just downloaded OS 3.1 so I could use voice control to place a call on my iPhone, but it's not working. Does this only work on the 3GS? I'm not sure if I have the 3G or 3GS, how can I tell?

  • Package batch renaming and relinking duplicates

    A plug-in/script available for InDesign to package some folders indd files into one folder with .indd, .pdf, .idml, links and fonts in folder, if images are duplicated between documents, rename with suffix "_1, _2, .... I need it to rename and relink

  • How can I get reimbursed for an accidental charge?

    How do you get reimbursed on your Apple account for an accidental charge related to purchasing a TV series in the wrong language?

  • Running PC CS4 suite on Snow Leopard using Parallels

    Hi.  I have a gig coming up where I will need to do some overnight video editing while on location at the end of the day for the next day's show.  I would like to purchase a Macbook with Snow Leopard for this purpose (up to now I've been strickly PC