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();

Similar Messages

  • How to implement a linked list in oracle ?

    HI All
    I want to know if there a way to implement a linked list in oracle ?
    Thanks in Advanced
    Naama

    A linked list is an array of the relevant data plus an indicator of the next and previous entries, right?
    Sounds easily achievable with any of the plsql collection types.
    The simplest would be a plsql associative array of a record
    Assignments of records in collections is always a bit hamfisted compared to sql objects types though (IMO).
    Something like ?
    DECLARE
    TYPE r_payload IS RECORD
    (col1 number,
      col2 number);
    TYPE r_array_entry is RECORD
    (prev_entry PLS_INTEGER,
      next_entry PLS_INTEGER,
      payload    r_payload);
    TYPE t_array IS TABLE OF r_array_entry INDEX BY PLS_INTEGER;
    v_array t_array;
    BEGIN
    NULL;
    END; 
      The use case for such a structure in properly coded SQL & PL/SQL is possibly the harder question.

  • Implementing Double Linked Lists

    I have been set a task creating a java class to implement the data cells of a double linked list, then improving on this class so that it will implemt the interface of a LinearList using a double linked list.
    HELP?!?!?!?!

    i have implemented a small method.u can implement the remaining methods as u want. I have not tested the code. Just for idea i am giving it. try it.
    public class Node{
         Node leftNode;
         Node rightNode;
         int data;
         public Node addNode(Node node,int data,int position){
              Node originalCopy=node;
              for(int i=0;i<position;i++){
                   Node tempNode=new Node();
                   tempNode.data=data;
                   tempNode.leftNode=node;
                   tempNode.rightNode=node.rightNode;
                   node=node.rightNode;
              return originalCopy;
    This class represents a Doubly linked list and it provides operations on it.

  • Help using javas inbuilt Linked List class

    I'm trying to create a LL of ints using Javas inbuilt LL class.
    I declared it using it: LinkedList test = new LinkedList();
    Now the Java API says it takes objects, is there a way of declaring the LL so that it takes ints, or a way of adding ints to the above LL?
    Thanks

    Integer.valueOf(int) gives an Integer object that wraps the int. If you're using >= 5.0, then autoboxing will do that for you, so you can just do list.add(someInt); Note, however, that it's still an Integer object, that's being stored, not an int primitive. If you want to store primitives, you'll have to define your own class or download a third-party one.

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

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

  • Please help me :'( , I really need help in Linked List & Recursion program.

    Hi everybody..
    I hope all of you are ok..
    I'm new member in this forum and I hope anyone can help me in Linked List $ Recursion issue..
    I should write a Java program that implements a linked list of objects. This program / class will have the following methods:
    1- //print each node starting from startNode upto the end node in the list
    void writeList(Node startNode)
    2- //insert a new element to the end of the list
    void insertEnd(Object element)
    3- //Print each element statring from first element in list to the last element then start //printing each element from the last element to the first element
    void writeMirror()
    4- //delete the last node.
    void deleteEnd()
    5- //returns the number of the nodes in the list.
    int lengthList(ListNode x)
    Implement the above methods using the following restrictions:
    1- All above methods must be implemented as a recursive method.
    2- For the given linked list class, there is only a head reference
    variable, pointing the beginning of the list. Thus there is no last or
    end reference variable.
    I don't know how to write this program :'( ..
    I need your help guys and I will be so happy if anyone can do it for me ..
    The sad girl
    MaRia :(

    Any body can give me any idea any hint that may help
    me ??Hint that will help you: get a personal tutor. This is the wrong place to learn how to program. And you definitely won't learn by having your homework done for you.
    Oh, and I don't care at all that your hamster has diarrhea, your boyfriend broke up with you, both of your parents are dead and unemployed, that you have to look after your 231 siblings all by yourself and that you're forced to take this class and rather want to do something completely different.
    Heard it all before.

  • Write two functions to find the the number of elements in a linked list?

    I am trying to Write two functions to find the the number of elements in a linked list. One method using recursion and One method using a loop...
    //The linked List class is Represented here.
    public class lp {
    public int first;
    public lp rest;
    public lp(int first1, lp rest1)
    first = first1;
    rest = rest1;
    The program i wrote so far is
    import java.util.*;
    import linklist.lp;
    public class listCount{
    //loop function
    public static void show_list(lp list)
    int counter = 0;
    while(list != null)
    list = list.rest;
    counter++;
    System.out.println ("length computed with a loop:" + counter);
    //recursive function
    public static int recursive_count(lp list)
    if (list.first == null)
    return 0;
    else
    return recursive_count(list.rest) + 1;
    //main method
    public static void main (String args[])
    lp list1 = new lp(1, new lp(2, new lp(3, null)));
    show_list(list1);
    System.out.println("length computed with a recursion:" +
    recursive_count(list1));
    at the if (list.first == null) line i get the error " incomparable types:
    int and <nulltype>" I know this is a beginners error but please
    help...What should I do?

    byte, char, short, int, long, float, double, and boolean are primitives, not objects. They have no members, you cannot call methods on them, and they cannot be set to or compared with null.

  • How to add different data types in Linked list?

    The basic idea is that I want to implement a linked list like the one which we generally implement in C. I need to store different data types in a single node. Is it possible to implement like this or I have to implement a linked list for each different data type?

    I have an application program in which there is a form. In this form there are different text fields in which data is to be inserted by the user. These data's will be inserted into the database. I want to hit the database only once. So I need to store these data in a data structure before I insert into the database. I think it will be easy for me to handle the data in a linked list if I can have different data types in a single node.
    Moreover, I think u're not getting my question. This pic will help u.
    http://img522.imageshack.us/img522/4500/sampler.jpg
    I'm not sure about that the code which u have written will have different data types in single node. I have to try that.
    And of course if anyone has any better idea than me, it will be very helpful.

  • 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

  • Remove element in linked list linked list

    here's my codes
    public class Student
        private String name, matric;
        public Student(){}
        public Student( String name, String matric)
           this.name = name;
           this.matric = matric;
         public String getName()
         { return name;}
         public void setName(String name)
         { this.name = name;}
         public String getMatric()
         { return matric;}
         public void setMatric( String matric)
         { this.matric = matric;}
         public String toString()
            return "Name: " + name + ", Matric no: " + matric + "\n";   
        }// end student classthe link list class
    public class LinkedList extends java.util.LinkedList
        // instance variables - replace the example below with your own
        private ListNode firstNode;
        private ListNode lastNode;
        private ListNode currNode;
        private String name;
         * Constructor for objects of class LinkedList
        public LinkedList(String s)
            name = s;
            firstNode = lastNode = currNode = null;
        public LinkedList() {this("list");}
        public synchronized void insertAtFront(Object insertItem) {
            if (isEmpty())
                firstNode = lastNode = new ListNode(insertItem);
            else
                firstNode = new ListNode(insertItem, firstNode);
        public synchronized void insertAtBack(Object insertItem) {
            if (isEmpty())
                firstNode = lastNode = new ListNode(insertItem);
            else
                lastNode = lastNode.next = new ListNode(insertItem);
        public synchronized Object removeFromFront() throws EmptyListException {
            Object removeItem = null;
            if (isEmpty())
                throw new EmptyListException(name);
                removeItem = firstNode.data;
                if (firstNode.equals(lastNode))
                    firstNode = lastNode = null;
                else
                    firstNode = firstNode.next;
                return removeItem;    
        public synchronized Object removeFromBack() throws EmptyListException {
            Object removeItem = null;
            if (isEmpty()) throw new EmptyListException(name);
            removeItem = lastNode.data;
            if (firstNode.equals(lastNode))
                firstNode = lastNode = null;
            else {
                ListNode current = firstNode;
                while (current.next != null)
                    current = current.next;
                lastNode = current;
                current.next = null;
            return removeItem;
        public synchronized boolean isEmpty()
        { return firstNode == null;}
        public synchronized Object getFirst() {
            if (isEmpty())
                return null;
               else {
                    currNode = firstNode;
                    return currNode.data;
        public synchronized Object getNext() {
            if (currNode != lastNode) {
                currNode = currNode.next;
                return currNode.data;
            else
                return null;
        public synchronized String print() {
            String out = "";
            if (isEmpty()) {
                out = "Empty "+ name;
            out = "The "+ name+ " is:\n";
            ListNode current = firstNode;
            while (current != null) {
                out += ""+ current.data.toString();
                current = current.next;
            return out;
        public synchronized Object getLast() {
            if (isEmpty())
                return null;
            else {
                currNode = lastNode;
                return currNode.data;
    }// end LinkedListand the application class
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class StudentAppLL
        public static void main(String[] args) throws IOException {
            LinkedList std = new LinkedList();
            BufferedReader br = new BufferedReader(new FileReader("studentIn.txt"));
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("studentOut.txt")));
            String line = br.readLine();
            while (line != null) {
                StringTokenizer tk = new StringTokenizer(line);
                while (tk.hasMoreTokens()) {
                    String n = tk.nextToken();
                    String m = tk.nextToken();
                    Student a = new Student(n, m);
                    std.insertAtFront(a);
                    line = br.readLine();
            std.print();
            System.out.print(std.getFirst());
            Student data = (Student)std.getFirst();
            String matric;
            String nm = "Zaki";
            while (data != null) {
                if (data.getName().equalsIgnoreCase(nm)) {
                    System.out.print(data.getName()+ " ada\n");
                    //std.re
                    data = (Student)std.getNext();  
            Student b = new Student("Umar","2004163943");
            std.insertAtBack(b);
            String name = "", matric = "", s = "";
            boolean stop = false;
            int size = std.size();
            JOptionPane.showMessageDialog(null, size);
            s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
            while(!stop){
                if (s.equalsIgnoreCase("A")){
                    name = JOptionPane.showInputDialog("Enter student name: ");
                    matric = JOptionPane.showInputDialog("Matric number: ");
                    Student student = new Student(name, matric);
                    std.insertAtBack(student);
                    s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
                else if (s.equalsIgnoreCase("R")){
                    Student data = (Student)std.getFirst();
                    Student first = (Student)std.getFirst();
                    Student last = (Student)std.getLast();
                    JOptionPane.showMessageDialog(null, "First: "+ first+ "\nLast: "+ last);
                    String ns = JOptionPane.showInputDialog("Enter the student's name");
                    while (data != null) {
                        // buang kalau pd bhgn dpn
                        if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(first.getName())) {
                            JOptionPane.showMessageDialog(null, first.getName());
                            JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
                            //std.removeFromFront();
                            std.remove(data);
                            s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");                                       
                         if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(last.getName())) {
                            std.removeFromBack();
                            JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
                             s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
                         data = (Student)std.getNext();  
                    }// habis while loop
                // keluar jika pilih 's'
                else if (s.equalsIgnoreCase("S")){ stop = true;}
                else { JOptionPane.showMessageDialog(null, "Wrong input"); }                    
            JOptionPane.showMessageDialog(null, std.print());
            br.close();
            pw.close();
        }// end main class
    }and here's the studentIn.txt data
    Ahmad 2004199877
    Hanif 2005378219
    Zaki 2004456790
    how can i do it? i mean to remove other than first element?
    Message was edited by:
    ikki_72

    > public class LinkedList extends java.util.LinkedList
    // instance variables - replace the example below with your own
    private ListNode firstNode;
    private ListNode lastNode;
    private ListNode currNode;
    private String name;
    [ ... ]Eeeeeeeeeew! Don't do that ever again! A java.util.LinkedList is very
    well capable of managing a linked list (it is a linked list after all).
    Either build your own linked list mechanics or use a LinkedList as
    one of the member variables of your class, but please don't do this.
    kind regards,
    Jos ( ... that was scary ... )

  • 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

  • Link List question

    This is more of a development question rather than programming I hope its not wrong to post it here. I apologize if I did
    I am developing a Linked List class that handles a list however, there is a potential (in fact almost a certainty) that the nodes could call to itself and cause an endless loop if running through the it. Any suggestion on how to handle such a case ?

    It's kind of hard to say without more details, but the two general approaches that pop to mind are:
    1) Document it. If the user chooses to ignore the docs, they get bad--posisbly undefined--behavior, and that's their problem.
    2) On every relevant operation, do a search for cycles. Keep track of which nodes you've touched so far. Since the size of the list (and hence the length of a cycle) is theoretically unbounded, and searching every possible path for cycles in a large or complex list (which sounds more like a graph than a list) can take mucho time and/or memory, you'll have to set an upper bound on how deep you'll search. If there's a cycle whose path length is longer than this depth, then you're back to #1 anyway.

  • Link list problem

    I have one link list class. Each record holds only one data.
    Now I am going to modify it. Each record holds two real numbers.
    how to do it?
    Thanks
    class ListNode
       // package access members; List can access these directly
       Object data;   
       ListNode nextNode;
       // constructor creates a ListNode that refers to object
       ListNode( Object object )
          this( object, null );
       } // end ListNode one-argument constructor
       // constructor creates ListNode that refers to
       // Object and to next ListNode
       ListNode( Object object, ListNode node )
          data = object;   
          nextNode = node; 
       } // end ListNode two-argument constructor
       // return reference to data in node
       Object getObject()
          return data; // return Object in this node
       } // end method getObject
       // return reference to next node in list
       ListNode getNext()
          return nextNode; // get next node
       } // end method getNext
    } // end class ListNode
    // class List definition
    public class List
       private ListNode firstNode;
       private ListNode lastNode;
       private String name; // string like "list" used in printing
       // constructor creates empty List with "list" as the name
       public List()
          this( "list" );
       } // end List no-argument constructor
       // constructor creates an empty List with a name
       public List( String listName )
          name = listName;
          firstNode = lastNode = null;
       } // end List one-argument constructor
       // insert Object at front of List
       public void insertAtFront( Object insertItem )
          if ( isEmpty() ) // firstNode and lastNode refer to same object
             firstNode = lastNode = new ListNode( insertItem );
          else // firstNode refers to new node
             firstNode = new ListNode( insertItem, firstNode );
       } // end method insertAtFront
    public static void main( String args[])
                 List list1 = new List();
                 int array1[] = { 160, 591, 114, 229, 230, 270, 128, 1657, 624, 1503 };
                                         //insert numbers in list
                 for (int c1 = 0; c1 < array1.length; c1++ )
                     list1.insertAtFront(array1[ c1 ]);
    ...

    ok, there we go.
    I modified a little.
    I added a class.
    public class data
        private double x;
        private double y;
        public data(double x,double y)
        x=this.x;
        y=this.y;
    }in main program
    public static void main( String args[] )
          List list = new List(); // create the List container
          data x1 =new data(9,-9);
          list.insertAtFront( x1 );
          list.print();
          data x2 =new data(8,-8);
          list.insertAtFront( x2 );
          list.print();
          data x3 =new data(7,-7);
          list.insertAtBack( x3 );
          list.print();
          data x4 =new data(6,-6);
          list.insertAtBack( x4 );
          list.print();
    ...Do I need change print method, some errors occuried.
    public void print()
          if ( isEmpty() )
             System.out.printf( "Empty %s\n", name );
             return;
          } // end if
          System.out.printf( "The %s is: ", name );
          ListNode current = firstNode;
          // while not at end of list, output current node's data
          while ( current != null )
             System.out.printf( "%s ", current.data );
             current = current.nextNode;
          } // end while
          System.out.println( "\n" );
       } // end method print
    } // end class List

Maybe you are looking for

  • Partial Pick Confirming Sales Order

    Hi Folks, I have a requirement where I have to Pick Confirm and Ship confirm Sales Order through API. 1. When the quantites to be picked are same as quantity ordered the code seems to work just fine. But suppose in my example my quantity in SO line i

  • Information about javascript in pdf forms

    Hello folks. Could anybody tell me where i can find information about application javascript language in pdf forms? I've visited adobe.com and found a lot of pdf articles but they are really useless. I want to find about object model of pdf form, abo

  • Video hangs after burning on a DVD

    Hi, after burning a project with menus and several chapters, I notice the DVD is hanging after a few chapters. My DVD burner itself should be ok, I got no hardware failures and it's working fine with Nero Burning ROM. Any suggestions?? Tx a lot, Kris

  • On chain-request and input

    Hi Experts                Can you pls explain me whats the difference between     on chain-request and on chain-input.             I tried both in a situation, but not able to find the differenciation.            Pls advise me with suitable example.

  • Source Code Longer Than Table --Dump. Wht to do?

    Hi All, I have created a Z-subrouitne pool and coded print program with Entry rountines for smartforms in it. When I tried to maintian the output control, stating the name of program and entry rountine of it, it is throwing dump while saving. it is s