Appending a singly linked list

I need to append a linkList ie- add another node onto the end of a linked list. I am rather new at this and would appreciate the help, thnaks.

Refer to java docs java.util.LinkedList class.
If you dont have the java docs download it from the site.
Advice: You should always have java docs at hand
Ironluca

Similar Messages

  • Sorting singly linked list with minimum time complexity

    Hi ...
    anyone could tell me how can i sort singly linked list with minimum time complexity .... ????
    Regards...

    By MergeSort or QuickSort O(n log n). But then you
    have to first extract the objects in the list,sort
    them, then rebuild the list. But it will still bealot
    faster than by keeping the list linked.Technically, I believe insertion sort is marginally
    faster for small n ( <20 or so).Woohoo! So for 20 out of the possible 2147483648 array
    sizes Insetion is faster!
    Unfortunately, checking for that case probably wastes
    all the time you get from using the faster sort...
    That would depend on the actual distribution off array sizes. So it's an engineering decision.
    Sylvia.

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • Single Linked List

    Hi Guys,
    I am trying to create a single linked list with one node pointing to the other. Then I have to create a method that displays the contents of the nodes. This method must take the head of the linked list as a parameter.
    I have created a class called node to store the data of each node created: This is the class;
    public class Node {
        String data;
        Node next;
        public Node(String data) {
            setData(data);
            setNext(null);
        } // Constructor
        public void setData(String data) {
            this.data = data;
        public void setNext(Node next) {
            this.next = next;
        public String getData() {
            return data;
        public Node getNext() {
            return next;
        public String toString() {
            if(data == null)
                return "Node: null";
                else
                return "Node: " + data.toString();
    }The second class is LinkedList which initialises each node and creates the linked list.
    public class LinkedList {
        private Node head;
        public LinkedList() {
            setHead(null);
        } // constructor
        private void setHead(Node head) {
            this.head = head;
        } // setHead
        private Node getHead() {
             return head;
        } // getHead
        public void add(String data) {
            if(getHead() == null){
                Node temp = new Node(data);
                temp.setNext(getHead());
                setHead(temp);
            else
                add(getHead(), data);
        } // add
        public static void main (String args[]){
            Node n1 = new Node();
            n1.setData("Jane");
            if (getHead() == null){
                setHead(n1);
            }else{
            System.out.println ("No initialisation of Linked List");
            n1.setNext(n2);
            Node n2 = new Node();
            n2.setNext(n3);
            n2.setData("Maria");
            Node n3 = new Node();
            n3.setNext(n4);
            n3.setData("Paul");
            Node n4 = new Node();
            n4.setData("Charlene");
    }Am I on the right track? And how can I create the method to display all the nodes which takes the head of the list as a parameter only?
    Thanks a lot

    doobybug wrote:
    The code I posted compiled.Then pls fix me errors:
    LinkedList.java:24: add(java.lang.String) in LinkedList cannot be applied to (Node,java.lang.String)
                add(getHead(), data);
                ^
    LinkedList.java:29: cannot find symbol
    symbol  : constructor Node()
    location: class Node
            Node n1 = new Node();
                      ^
    LinkedList.java:31: non-static method getHead() cannot be referenced from a static context
            if (getHead() == null){
                ^
    LinkedList.java:32: non-static method setHead(Node) cannot be referenced from a static context
                setHead(n1);
                ^
    LinkedList.java:35: cannot find symbol
    symbol  : variable n2
    location: class LinkedList
                n1.setNext(n2);
                           ^
    LinkedList.java:36: cannot find symbol
    symbol  : constructor Node()
    location: class Node
                Node n2 = new Node();
                          ^
    \LinkedList.java:37: cannot find symbol
    symbol  : variable n3
    location: class LinkedList
                n2.setNext(n3);
                           ^
    LinkedList.java:39: cannot find symbol
    symbol  : constructor Node()
    location: class Node
                Node n3 = new Node();
                          ^
    LinkedList.java:40: cannot find symbol
    symbol  : variable n4
    location: class LinkedList
                n3.setNext(n4);
                           ^
    LinkedList.java:42: cannot find symbol
    symbol  : constructor Node()
    location: class Node
                Node n4 = new Node();
                          ^
    10 errors

  • Help With Data Structures (Singly Linked Lists)

    Need help inserting user entered name alphabetically into SSL
    import java.util.Scanner;
    class SLLNode<T> {
        public T info;
        public SLLNode<T> next;
        public SLLNode() {
            next = null;
        public SLLNode(T el) {
            info = el; next = null;
        public SLLNode(T el, SLLNode<T> ptr) {
            info = el; next = ptr;
    class SLL<T> {
        protected SLLNode<T> head, tail;
        public SLL() {
            head = tail = null;
        public boolean isEmpty() {
            return head == null;
        public void addToHead(T el) {
            head = new SLLNode<T>(el,head);
            if (tail == null)
                tail = head;
        public void addToTail(T el) {
            if (!isEmpty()) {
                tail.next = new SLLNode<T>(el);
                tail = tail.next;
            else head = tail = new SLLNode<T>(el);
        public T deleteFromHead() {
            if (isEmpty())
                 return null;
            T el = head.info;
            if (head == tail)      
                 head = tail = null;
            else head = head.next;
            return el;
        public T deleteFromTail() {
            if (isEmpty())
                 return null;
            T el = tail.info;
            if (head == tail)     
                 head = tail = null;
            else {                 
                 SLLNode<T> tmp;   
                 for (tmp = head; tmp.next != tail; tmp = tmp.next);
                 tail = tmp;       
                 tail.next = null;
            return el;
        public void delete(T el) { 
            if (!isEmpty())
                if (head == tail && el.equals(head.info))
                     head = tail = null;     
                else if (el.equals(head.info))
                     head = head.next;   
                else {                   
                     SLLNode<T> pred, tmp;
                     for (pred = head, tmp = head.next;
                          tmp != null && !tmp.info.equals(el);
                          pred = pred.next, tmp = tmp.next);
                     if (tmp != null) {  
                         pred.next = tmp.next;
                         if (tmp == tail)
                            tail = pred;
        public void printAll() {
            for (SLLNode<T> tmp = head; tmp != null; tmp = tmp.next)
                System.out.print(tmp.info + " ");
        public boolean isInList(T el) {
            SLLNode<T> tmp;
            for (tmp = head; tmp != null && !tmp.info.equals(el); tmp = tmp.next);
            return tmp != null;
    class Passengers extends SLL<String>{
         Scanner kb = new Scanner (System.in);
         String name;
         Passengers(){
         void reserveTicket(){
              SLLNode<String> temp;
              System.out.println("Please enter your Last Name");
              name = kb.next();
              if(isEmpty())
                   addToHead(name);
              else
                   if(name.compareTo(head.info) <= 0)
                        addToHead(name);
                   else
                        if(name.compareTo(head.info) > 0){
                             while(head.next == null){
                                  temp = head.next;
                                  name.compareTo(temp.info);
                                       if(name.compareTo(temp.info) <= 0)
                                            temp.info = name;
         void cancelReserve(){
              System.out.println("Please enter your Last Name");
              name = kb.next();
              if(isInList(name)){
                   delete(name);
                   System.out.println("Your reservation has safely been removed");
              else System.out.println("That reservation does not exist");
         void checkReserve(){
              System.out.println("Please enter your Last Name");
              name = kb.next();
              if(isInList(name)){
                   System.out.println("You currently have a reservation for this flight");
                   printAll();
              else System.out.println("Sorry, there is no reservation for this flight under that name");
         void showPassengers(){
              if(! isEmpty())
                   printAll();
              else System.out.println("There are no passengers for this flight");
    class Program2_19{
         public static void main(String[] a) {
              Passengers passList = new Passengers();
              Scanner kb = new Scanner (System.in);
              int choice;
              int option = 1;
              while(option == 1){
                   System.out.println("Push 1 to Reserve a ticket");
                   System.out.println("Push 2 to Cancel a reservation");
                   System.out.println("Push 3 to Check reservations");
                   System.out.println("Push 4 to Display all passengers");
                   choice = kb.nextInt();
                   System.out.println();
                   if(choice == 1)
                        passList.reserveTicket();
                   else if(choice == 2)
                        passList.cancelReserve();
                   else if(choice == 3)
                        passList.checkReserve();
                   else
                        passList.showPassengers();
              System.out.println("Would you like to perform another action?");
              System.out.println("Press 1 for yes, or 2 for no");
              option = kb.nextInt();
              System.out.println();
    }

    how do i step thru my list to find the correct spot to insert the name...I kno it has to be done with compareTo() but what do i compare the name with?..the node?.. the head? the tail?

  • Changing data in a linked list object.

    hi,
    i'm still pretty new to java, so bear with me if i am making stupid mistakes, heh.
    i'm having trouble with changing data in an object stored in a singly-linked list. i've created a class that will store polynomials in sorted order (descending) in a singly-linked list. each linked list is one polynomial, and each node references to a polynomial object that stores two ints: the coefficient and the exponent of that term.
    i'm having trouble when it comes to 'collecting like terms,' though. here's a rough skeleton of my code:
    public class Polynomial
    private LinkedList polynoList;
    private LinkedListItr Itr;
    private int coeff;
    private int exponent;
    public Polynomial()
    zeroPolynomial();
    } // this constructor sets up an empty linked list
    public Polynomial( int c, int e )
    coeff = c;
    exponent = e;
    } // this creates a Polynomial object storing the two ints
    public void zeroPolynomial()
    polynoList = new LinkedList();
    theItr = polynoList.zeroth();
    } // this method creates the empty linked list and sets the
    //iterator on the zeroth node.
    //various other methods are here, not relevant to my post
    //this next method is the one i am having trouble with.
    //it takes two ints as parameters, the coefficient
    //and the exponent.
    public void insertTerm( int c, int e )
    //...i have a few if/then statements here
    //so that the terms can be inserted in descending order.
    LinkedListItr tester = polynoList.first();
    //the 'tester' iterator is set on the first node
    //this following if statement retrieves the exponent
    //in the current node by casting the information
    //retrieved from the LinkedList retrieve() method
    //into Polynomial, then compares it to the current
    //exponent. if they are equal, i want to add the
    //coefficients.
    if( e == ((Polynomial)tester.retrieve()).getExp() )
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    //a main method goes here wherein the user can insert
    //terms, print the polynomial, etc.
    }//end Polynomial class
    can anyone help me out? the code i'm using compiles correctly, but it does not change the value of the current coeff variable as i'd like to think it should. any input would be GREATLY appreciated, thanks!

    hey,
    thanks for the reply...
    i am sure that ((Polynomial)tester.retrieve()).getExp() will return an int equal to 'e.' i tried this:
    System.out.println("e="+e);
    System.out.println((Polynomial)tester.retrieve()).getExp());
    if( e == ((Polynomial)tester.retrieve()).getExp() ){
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    System.out.println( "this.coeff = " + this.coeff );
    with that, the output showed that e and the getExp() output were the same. it also showed (as output) that this.coeff did change in value, but when i tried this:
    System.out.println( ((Polynomial)tester.retrieve()).getCoeff() )
    to check if the value changed within the object, it didn't. this.coeff changed, but the actual coeff variable in the object didn't.
    any ideas?

  • Single linked adding element help

    i just started working with singley linked lists and i am having trouble figuring out how to add an element.
    here is what i have so far
    public class LinkedIntList implements IntList {
         protected class Node {
              protected int data;
              protected Node next;
              protected Node() {
                   data = 0;
                   next = null;
         protected Node head;
         protected int size;
         public void add(int element)
              // i can't figure out how to add an element to the list...
    }     

    A simple add() method in a singly linked list class will add a Node to the last Node in the chain. So the linked list class needs to keep track of the last Node--just like it keeps track of the first Node.
    Adding a node will simply require that you assign the new Node to the last Node's next member. Then you set the linked list's last variable equal to the new node.
    Note that you could implement the add method by starting at the head and using the Node's getNext() method to obtain the object stored in the Node's next variable. That will be the next Node in the chain, and then you can use getNext() on that Node to get its next variable, etc., until you finally come upon a Node whose next member is equal to null. Then you add the new Node to the Node whose next variable is equal to null.

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

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

  • Addition in a linked list

    Hi,
    I want to add numbers in a linked list. For example when i pass in the string 123456789, i reverse it so that it appears as 987654321 in the linked list. If i add this to the string 954 which appears as 459 in the linked list, i am supposed to get 123457743 but i get 1743. How do i rectify this from my code.
    import java.util.LinkedList;
    import java.util.ListIterator;
    public class LargeInteger {
    /** Constructs a new LargeInteger object from the specified String.
    * The String parameter will contain the digits comprising the number
    * to be represented by this LargeInteger object. The number may be
    * either positive or negative, so be sure to check for a sign.
    * You should throw an IllegalArgumentException if the string which is
    * passed in does not contain a valid number. An invalid String would
    * be one which contains any character other than a digit (however the
    * first character may be a negative sign).
    * @param value A String representing the number to be represented.
    &nbs! p; * @throws IllegalArgumentException This exception is thrown if the
    * parameter doesn't contain a valid number.
    LinkedList digits = new LinkedList();
    public LargeInteger(String value) throws IllegalArgumentException {
    //Declare variables
    boolean neg = false;
    int num = 0;
    int start = 0;
    char ch = ' ';
    Integer tempObj = new Integer(num);
    //If the first character is not a - sign or it is less than the character 0
    //or it is greater than the character zero, then throw
    //IllegalArgumentException
    //else add digits into linked list as integers
    if(value.startsWith("-")) {
    neg = true;
    start = 1;
    } else if ( !Character.isDigit(value.charAt(0)) ) {
    throw new IllegalArgumentException();
    for (int j = value.length()-1; j >= start; j--) {
    ch = value.charAt(j);
    if (Character.isDigit(ch)) {
    num = Character.getNumericValue(ch);
    tempObj = new Integer(num);
    digits.add(tempObj);
    } else {
    throw new IllegalArgumentException();
    } // end Constructor
    public static void main(String[] args) {
    LargeInteger a = new LargeInteger("954");
    LargeInteger b = new LargeInteger("123456789");
    LargeInteger c = a.plus(b);
    System.out.println( c.toString() );
    System.out.println( a.toString() );
    System.out.println( b.toString() );
    /** Calculates the sum of this LargeInteger object with the one passed
    * as a parameter.
    * @param other The number to add to the current value.
    * @return The sum of this LargeInteger and the value passed as a
    * parameter.
    public LargeInteger plus(LargeInteger other) {
         int i = 0;
    LargeInteger result = new LargeInteger("0");
    int carry = 0;
    ListIterator onfiltered = digits.listIterator();
    ListIterator two = other.digits.listIterator();
    //Add digits in linked list
    for (; i < digits.size() && i < other.digits.size(); i++) {
    result.digits.addFirst(
    new Integer(
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    % 10));
    carry =
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    / 10;
    onfiltered.next();
    two.next();
    //Append any remaining digits from this value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)digits.get(i)).intValue() + carry) / 10;
         onfiltered.next();
    //Append any remaining digits from the other value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)other.digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)other.digits.get(i)).intValue() + carry) / 10;
         two.next();
    if(carry != 0){
         result.digits.addFirst(new Integer(carry));
    return result;
    } // end plus

    Use a debugger.
    Or put in some debugging statements.

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

  • Linked List and String Resources

    Linked Lists can be very slow when removing dynamic Strings.
    If you add and remove Strings in the
    following way, the performance is very poor:
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    - If you add and remove the not dynamic String: "" + 10000 instead,
    - or do not remove the String (but add it in the middle),
    - or use a ArrayList
    the performance is much better.
    I suppose it depends on handling the String resources.
    If you run the following class, you will see what I mean:
    public class SlowLinkedList
    public static void main (String[] args)
    // Be carefull when accessing/removing Strings in a Linked List.
    testLinkedList ();
    testLinkedListHardCodedString();
    testLinkedListNoRemove();
    testArrayList();
    testArrayListNoParam();
    private static void testLinkedList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time dynamic String remove " + time);
    private static void testLinkedListHardCodedString ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time same String remove " + time);
    private static void testLinkedListNoRemove ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new LinkedList();
    for (int i = 0 ; i < n ; i++)
    list.add (i/2, "" + n);
    time = System.currentTimeMillis () - time;
    System.out.println ("time add dynamic String " + time);
    private static void testArrayList ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + n);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList " + time);
    private static void testArrayListNoParam ()
    int n = 10000;
    long time = System.currentTimeMillis ();
    List list = new ArrayList ();
    for (int i = 0 ; i < n ; i++)
    list.add ("" + 10000);
    for (int i = n-1 ; i >= 0 ; i--)
    list.remove(i/2);
    time = System.currentTimeMillis () - time;
    System.out.println ("time ArrayList same String " + time);
    A typic output of the Performance is:
    time dynamic String remove 1938
    time same String remove 312
    time add dynamic String 31
    time ArrayList 63
    time ArrayList same String 31

    begin long winded reply
    It doesn't matter if they are Strings or any other Object. LinkedList, in the way you are executing
    remove, is not effecient. The LinkList remove will look at the index, if it is less than the median
    it will start iterating from 0, if it is greater, it will start iterating in reverse from the end. Since you
    are removing from the median, it will always take the longest (either forward or backward) to
    get to the middle. Whereas, ArrayList simply uses the arraycopy to drop the element from the
    array. The "NoRemove" test doesn't make sense to me in relation to the others.
    Also, the VM is performing optimizations when you hardcode the 'n' value to 10000, it seems
    that the VM won't optimize when using 'n'. Tusing Integer.toString(n), instead of "" + n,
    in the first test case, it will yield better results.
    My profs in college drove collections into my head and removing from a linked list without
    an iterator is going to be inefficient. Iterators are a beautiful thing, use them.
    Try this code instead, it simulates your remove in the middle with an iterator and, on my
    machine, is faster than the ArrayList.
    private static void testLinkedList() {
        int n = 10000;
        long time = System.currentTimeMillis ();
        List list = new LinkedList();
        for (int i = 0 ; i < n ; i++) {
            list.add (Integer.toString(n));
        boolean forward = false;
        for (ListIterator li = list.listIterator(n >> 1); li.hasNext() || li.hasPrevious();) {
            if (forward) {
                li.next();
                forward = false;
            } else {
                li.previous();
                forward = true;
            li.remove();
        time = System.currentTimeMillis () - time;
        System.out.println ("time dynamic String remove " + time);
    }One other thing, run the tests more than once in a single VM and take the average. You could
    apply some statistical analysis to figure out which is better within a certain confidence percentage,
    but that is probably overkill. :)
    Check the collection tutorial for more info: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html
    end long winded reply
    Matt

  • Linked List for custom insertion sorting not listing

    Hello fellow humans! :3 this is an assignment; the little menu's options are the tasks it's supposed to perform. Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. Cases 3 and 4 are completely useless without the first two; I've included them because being quite new I'd rather not exclude anything important.
    class with main method follows:
    package batch2;
    import java.io.*;
    class e21
    public static void main (String []args) throws IOException, NumberFormatException
    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    FromKeyboard key = new FromKeyboard();
    int a, option = 0, lrg;
    MyList alist, blist, clist;
    char fin = 'v';
    boolean avac, bvac, cvac, bord;
    NodeLD nodeaux = null;
    alist = new MyList();
    blist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'B', unsorted");
      System.out.println("3. Sort list 'B'");
      System.out.println("4. Mix lists 'A' & 'B' into a new sorted list 'C'");
      System.out.println("9. Exit");
      option = key.enterInt();
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          a = key.enterInt();
          if (a != -1){
            alist.insertToList(a);
            System.out.println("Test 1");     
          while (a != -1){
               a = key.enterInt();
            if (a != -1){
              System.out.println("Test 1.1");
              nodeaux = new NodeLD();
              nodeaux.theData(a);
              alist.sortInserList(nodeaux);
              System.out.println("Test 2, a="+a+"");
         System.out.println("List 'A', sorted by insertion:");
          alist.seeList();
        break;               
      case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
             System.out.println("Enter the integers you wish to add to list 'B'");
             System.out.println("Enter '-1' to finish");
             a = 0;
             while (a != -1){
                if (a != -1){
                  a = key.enterInt();
                  clist.insertToList(a);
             System.out.println("Unsorted list:");
             clist.seeList();
        break;
      case 3:
            while (clist.front != null){
          if (clist.front != null){
             blist.sortInserList(clist.front);
             clist.front = clist.front.givePrevious();
          System.out.println("List 'B', sorted");
          blist.seeList();
        break;
      case 4:
            while (blist.front != null){
         if (blist.front != null){
          alist.sortInserList(blist.front);
          blist.front = blist.front.givePrevious();
         System.out.println("List 'C', combining 'A' & 'B', sorted");
         clist.seeList();
        break;
      case 9:
         System.out.println("Program ended");
        break;
      default:
         System.out.println("Invalid option");
        break;
    while (option != 9);
    }Custom list class follows:
    package batch2;
    class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
           System.out.println(""+g.dat+"");
           g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         System.out.println("Test A");
         while (g.dat > pointer.dat && pointer != null){
           if (pointer.giveNext()!= null){
            pointer = pointer.giveNext();
            tag = false;
            System.out.println("Test A.b");
           else if (pointer.giveNext() == null) {
            tag = true;
            System.out.println("Test A.c");
           break;
         prepointer = pointer.givePrevious();
         if (pointer == null || tag){
           insertToList(g.dat);
           System.out.println("Test B. Pointer == null or tag == true");
         if (prepointer != null && !tag){
           g.thePrevious(prepointer);
           prepointer.theNext(g);
           System.out.println("Test C. prepointer != null && !tag");
         if (pointer != null && !tag){
           g.theNext(pointer);
           pointer.thePrevious(g);          
           System.out.println("Test D. pointer !=null && !tag");
         System.out.println("Test E. Right before return");
         return g.dat;
    }And here comes the accompanying Node class:
    package batch2;
    class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    }And last but not least, the part of FromKeyboard I'm using for this exercise, just in case:
    package batch2;
    import java.io.*;
    public class FromKeyboard
    public BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    public int enterInt(){
         System.out.flush();
         int integ = -1;
         try{
              integ = Integer.valueOf(input.readLine());
         catch(NumberFormatException e){
              System.err.println("Error: "+e.getMessage()+"");
         catch(IOException t){
              System.err.println("Error: "+t.getMessage()+"");
         return integ;
    }All help with regards as to why my lists aren't working and general comments/nudges on the sorting are welcome and appreciated.

    Hi Kevin, thank you for replying! I'll trim my code in a moment; as for a specific inquiry:
    >Sadly, case 1 only records the last valid (non -1) entry instead of building a list. case 2 does the same, except for actually recording the ending value (-1) instead of the last valid entry. >
    More direct approach to asking for help: These classes compile correctly and run, although the result is not what I'm aiming for: I get a single-noded list instead of the full list. Why isn't it keeping all the nodes but the last one only?
    Edited by: SquaredCircle on 09-Sep-2010 16:46
    That was fun :D this is my SSCCE for the main class:
    class e21SSCCE
    public static void main (String []args) throws NumberFormatException
    int a[] = {14, 25, 11, 43, 33, -1}, key[] = {1,2,9}, option = 0, i = 0, e = 0;
    MyList alist, clist;
    char fin = 'v';
    NodeLD nodeaux = null;
    alist = new MyList();
    clist = new MyList();
    do{
      System.out.println("Please choose an option:");
      System.out.println("1. Create list 'A' sorting by insertion");
      System.out.println("2. Create list 'C', unsorted");
    System.out.println("9. Exit");
      option = key[e];
      e++;
      switch (option){
      case 1: //this only records the last valid (non -1) entry D:
             System.out.println("Enter the integers you wish you sort in list 'A'");
          System.out.println("To finish, enter '-1'");
          i = 0;
          if (a[i] != -1){
            alist.insertToList(a);
         i++;
         while (a[i] != -1){
    if (a[i] != -1){
         nodeaux = new NodeLD();
         nodeaux.theData(a[i]);
         alist.sortInserList(nodeaux);
         i++;
         System.out.println("List 'A', sorted by insertion:");
         alist.seeList();
    break;               
    case 2: //this also keeps the last value, yet not a valid one but the '-1' for the ending condition
    System.out.println("Enter the integers you wish to add to list 'B'");
    System.out.println("Enter '-1' to finish");
    i = 0;
    while (a[i] != -1){
    if (a[i] != -1){
    clist.insertToList(a[i]);
                        i++;     
    System.out.println("Unsorted list:");
    clist.seeList();
    break;
    case 9:
         System.out.println("Program ended");
    break;
    default:
         System.out.println("Invalid option");
    break;
    while (option != 9);
    The cleaner version of the list class:class MyList
    boolean tag = false;
    protected NodeLD front;
    protected int size;
    public MyList(){
         front = null;
         size = 0;
    public void insertToList(int x){
         NodeLD t;
         t = new NodeLD();
         t.theData(x);
         t.theNext(front);
         if(front!=null){
              front.thePrevious(t);
         front = t;
         size++;
    public void seeList(){
         NodeLD g;
         g = front;
         System.out.println();
         while (g!=null){
              System.out.println(""+g.dat+"");
              g = g.givePrevious();
         System.out.println("=============================");
    public int sortInserList(NodeLD g){
         NodeLD pointer = new NodeLD();
         pointer = front;
         NodeLD prepointer = new NodeLD();
         while (g.dat > pointer.dat && pointer != null){
              if (pointer.giveNext()!= null){
                   pointer = pointer.giveNext();
                   tag = false;
              else if (pointer.giveNext() == null) {
                   tag = true;
                   break;
              prepointer = pointer.givePrevious();
              if (pointer == null || tag){
                   insertToList(g.dat);
              if (prepointer != null && !tag){
                   g.thePrevious(prepointer);
                   prepointer.theNext(g);
              if (pointer != null && !tag){
                   g.theNext(pointer);
                   pointer.thePrevious(g);          
         return g.dat;
    And the node class:class NodeLD
    private int data;
    private NodeLD next;
    private NodeLD previous;
    public int dat;
    NodeLD(){
         data = 0;
         next = null;
         previous = null;
         dat = data;
    public void theData(int x){
         data = x;
         dat = data;
    public void theNext(NodeLD y){
         next = y;
    public void thePrevious(NodeLD z){
         previous = z;
    public int giveData(){
         return data;
    public NodeLD giveNext(){
         return next;
    public NodeLD givePrevious(){
         return previous;
    I followed the SSCCE guideline, and tried my best with it. The indentation checker was a broken link, though :c.
    Edited by: SquaredCircle on 09-Sep-2010 17:12                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Getting null returned when working with Linked Lists

    Ok, i'm having the same problem with a couple of methods that deal with linked lists, and i was hoping someone could lend me a hand. First off, the specifications for one of the methods:
    An iterative procedure smallElements
    PARAMETERS: a ListItem reference, ls
    an integer n
    RETURN VALUE: a new list identical to the given list, except
    that it contains no occurrences of numbers greater than n.
    for example, given input list ( 3 2 6 3 4 ) and 3,
    the return value would be the list ( 3 2 3 )
    And here is my code:
    ListItem smallElements(ListItem ls, int n){
    ListItem small = null;
    ListItem result = small;
    if(ls == null)
    return null;
    else{
    while(ls!=null){
         if(ls.number <=n){
         result = new ListItem(ls.number, null );
         result = result.next;
         ls = ls.next;
    return small;
    Like the topic says, i keep getting null returned as a value. I have tried setting small= new ListItem(ls.number, null), and that actually returns the correct list, except that the first number is repeated twice. I would greatly appreciate any assistance.

    I am not sure I understand your code. What exactly are those ListItems? It seems to me that you are dealing with single List elements, while the specification says that you are supposed to return a List.
    But the main error is that you have two ListItem objects there, which seems to fill the same purpose - only that you use one, and return the other. 'small', which is the one you return, never get set to anything else than null.
    I think you should do something like this: make a new, empty list to return
    for element in parameterlist
        if number is smaller than n
            add this element to returnlist
    return returnlist

Maybe you are looking for

  • Prerequisites for Sender and Receiver FTP adapter

    Hi Experts, I am new to PI and configuring simple file to file scenario. I need to know the prerequsites for sender and receiver FTP adapter. Scenario is System A -> XI -> System B . What I want to know is: 1> What ports need to be opened? 2> Any ser

  • Now not able even to connect to iTunes store-  to do with iTunes7?

    over the past few weeks i have been able to at least search iTunes music without upgrading to iTunes7- starting yesterday, though, & all through today, i can't even get that far- get an error message which says the store may be busy & tells me to che

  • IControl error message in GB3

    Hi world. Just installed iLife06, fired up GB3 and got following error message: Module File "iControl copy' is outdated and cannot be used with this version of GarageBand Control Surfaces Please get an update of the module file and move it to "Midi D

  • Advanced Queuing for Oracle / Dequeue failed

    Hi *, I'm using Oracle Advanced Queuing and OC4J with some MDBs. Unfortunately sometimes I have following exception: 03-05-21 10:29 Error listening to 'USER_QUEUE' oracle.jms.AQjmsException: JMS-120: Dequeue failed      at oracle.jms.AQjmsError.throw

  • Get error message after trying all the fixes

    My hp psc 1315 all-in-one worked fine until today..trying to scan a doc got this error message -- An unexpected error has occurred. Check OK to close program, and then try the following: --restart the program --restart the PC and then try again --rei