Linked List Insertion Sort

Can anyone help me figure out the code for a linked list insertion sort by only manipulating the references? or provide me to a link that will.
I can't seem to get it going.
Thanks

Well, first you have to split this topic up into its two pertinent portions:
First, you have to know how to do an insertion sort. If you don't know how to do that, here's a good quick example:
http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/InsertSort.html
Next, you need to adapt this scheme to a linked list. The only real challenge here is knowing how to unlink an item in the list, relink it in the right place, and not disrupt the list. This is one of the first hits off google for the linked list:
http://cslibrary.stanford.edu/103/

Similar Messages

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Link List problems

    The code is supposed to go and get names from objects in a linked list, then sort them alphabeticaly, then put them into a new list.
    getNameAtCurrent returns a String, enqueue puts the ListNodes into a new LinkedList. showList prints out the entire list.
              int size = linker.length( );
              linker.resetIteration( );
              String[] nameSort = new String[size];
              for(int i = 0; i < size; i++)
                   nameSort[i] = linker.getNameAtCurrent( );
              for(int i = 0; i < size-1; i++)
                   String a = nameSort;
                   String b = nameSort[i+1];
                   if(a.compareTo(b) > 0)
                        String tempName = nameSort[i];
                        nameSort[i] = nameSort[i+1];
                        nameSort[i+1] = tempName;
                   else if(a.compareTo(b) == 0)
              LinkedListWithIterator nameSorted = new LinkedListWithIterator();
              for(int j = 0; j > size-1; j++)
                   nameSorted.enqueue(linker.Find(nameSort[j]));
              nameSorted.showList();

    public void enqueue(ListNode data) //Enqueues data
              if (head == null)
                   head = current = data;
              else
                   current = (current.link = data);
        }I guess this might be the main probelm with the entire bit of code. The list has 4 strings stored in it, and I guess I'm trying to find the ListNode that the sorted string is stored in and put those into a new LinkedList in the order that the sorted names were in.
    I have no clue if this works at all, but its just supposed to find the node that had the string in it and copy it to a new LinkedList

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • Merging two linked lists of integers that are sorted

    hey guys,
    i need to write a method to merge two linked lists of integers that are sorted into ascending order. the results should be a third linked list that is the sorted combination of the original lists.
    can someone help me start this? Basically, the method will be taking in two sorted linked lists of integers and merge them into one big sorted linked list.
    Im just looking to get some algorithm ideas and maybe one or two lines of pseudocode to get me started.
    thanks

    i can't destroy the original lists so im gonna need
    to create a new sorted list. then since both of the
    lists im using are sorted, i'll just have to copy one
    of them into the new list i created. Then i will get
    an item from the unused list and search that node in
    the new copied list and insert in appropriate
    position using the two Nodes...example(prev and
    curr).That can work. I'd probably do it by initializing a new list and compare the first items in each of the original lists, inserting the smaller in my new list and advancing to the next element in the original list from which I took the item, repeating the process until I copied each item from both original lists. Don't forget to take into account that you will reach the end of one list before the other.

  • Sorting My Linked List

    Alright, here's the problem. I have my linked list, either imported from a text file or inputted by the user. Now, I need to sort it by the date and the time strings... Yet, every time I do I get an NullPointException. Can anyone help? Here's my code for the list:
    public class ListReferenceBased implements ListInterface{
         //references to the linked list items
         private Node head;
         private int numItems; //number of items that exist in list
         //Default Constructor
         //sets both items to null
         public ListReferenceBased(){
              numItems = 0;
              head = null;
         //if the numItems in the list is empty
         //returns true.
         public boolean isEmpty(){     
              return numItems == 0;
         // returns numItems, aka the size of the list
         public int size(){
              return numItems;
         //finds a node by setting a node to the 'head'
         // and loops through to the index 'resetting'
         // curr to the 'next' node.
         private Node find(int index){
              Node curr = head;
              for( int skip = 1; skip < index; skip++){
                   curr = curr.getNext();
              return curr;
         public Object get(int index)
              throws ListIndexOutOfBoundsException{
              //catches if list does not reach the index given
              //loops through the index
              if(index >= 1 && index <= numItems){
              //sets curr to the index through find()
              Node curr = find(index);
              //sets dataitem to the current node
              Object dataItem = curr.getItem();
              return dataItem;
              }else{
              throw new ListIndexOutOfBoundsException("The List index is out of bounds on get");
         public void add(int index, Object item)
              throws ListIndexOutOfBoundsException{
              //checks to make sure there are no nodes yet
              //if there are inserts them in the list
              //by moving
              if(index >=1&& index<= numItems+1){
                   if(index==1){
                        // if no list exists
                        //creates a new node and sets it to head
                        Node newNode = new Node(item, head);
                        head = newNode;
                   }else{
                             //inserts the node at the index
                             //by finding it first
                             Node prev = find(index-1);
                   //creates a new node by placing the Object item
                   //and the 'new prev' node into a node
                   //'deleting' the old 'bonds'
                   Node newNode = new Node(item, prev.getNext());
                   rev.setNext(newNode);
                        //increments number of items in list
                        numItems++;
              }else{     
                        throw new ListIndexOutOfBoundsException("List index out of bounds");
         public void remove(int index)
              throws ListIndexOutOfBoundsException{
              //catches the list if it doesn't exist
              //checks to make sure list exists
              if(index>=1&& index<= numItems){
                   //if only the head exists
                   //calls next node else moves
                   //the node away and moves the prev
                   //on up.
                   if(index==1){
                        head = head.getNext();
                   }else{
                        Node prev = find(index-1);
                        Node curr = prev.getNext();
                        prev.setNext(curr.getNext());
                   //decreases the number of items in list
                   numItems--;
              }else{
         throw new ListIndexOutOfBoundsException("List index out of bounds");
         //sets the numItem to null telling the list it
         //does not exist
         public void removeAll(){
              head = null;
              numItems=0;
              

    Yeah, unfortunately, I had to design my own linked list for my assignment (that's taken almost 40+ hours). So, now every alogrithm I've tried to write seems to give me a null pointer, for example this one
    public void sort(){
              //loop through all existing nodes
              for(Node curr = head; curr != null; curr = curr.getNext()){
                   //parse the string of the current node
                   //to a string value
                   Node current = curr.getNext();
                   Node next = current.getNext();
                   Node temp;
                   String thisline = current.getItem().toString();
                   System.out.println(thisline);
                   StringTokenizer parser = new StringTokenizer ( thisline, "\t" );
                   String thisdate = parser.nextToken();
                   String thistime = parser.nextToken();
                   String thisline2 = next.getItem().toString();
                   System.out.println(thisline2);
                   StringTokenizer parser2 = new StringTokenizer ( thisline2, "\t" );
                   String thisdate2 = parser.nextToken();
                   String thistime2 = parser.nextToken();
                   //compares the dates of next in list
                   if(thisdate.compareTo(thisdate2)==1){
                        next.setNext(current);
                        current.setNext(next.getNext());
                        printList();
                        //if dates equal, compare the times
                   //if equal move to new position
                        //delete old position
    }Pretty much I believe moving the positions is causing the problems after the first run around. Any suggestions?

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Sort Linked List...

    I need help sorting a linked list.
    So far, in my sort method I have...
    public LinkedList sort();
    LinkedList newList = new LinkedList();
    Node ref;
    Node temp = new Node(head.getempID(); head.getempLast(), head.getempFirst(); head.getempDept(), head.getempSalary());
    for(ref = head; ref != null; ref.getNext());
    if(ref.getempID() <= temp.getEmpID());
    temp = (ref.getempID(), ref.getempLast(), ref.getempFirst(), ref.getempDept(), ref.getempSalary());
    newList.insert(temp); //???????
    return newList();
    // As you can tell, each one of my node's consists of an employee's id number, last name, first name, department, and salary...I need to sort the linked list by the employee's ID number. I can not figure out how to swap nodes though. PLEASE HELP A KID OUT!!!

    I was worng, my last data structure lecture today(I hope).
          |       |     |       |     |       |     |       |         |       |
    head->| Node1 |---->| Node2 |---->| Node3 |---->| Node4 |---etc-->| NodeN |->null
          |       |     |       |     |       |     |       |         |       |
    Q: How do you swap node2 with node3?
    A: Think about it!  Look at a picture if thats what you need. Draw the lines of reference to figure it out.
      1. Where does node1.next need to point to, how about node2.next, or node3.next?
      3. How do you change these without losing a node, are you going to need a temp?
      4. What about special case(switching node1 and node2)?
    This is simple problem solving skills.  I assume you have built the list yourself,
    so you have the basic knowledge base needed.

  • Sorting linked list

    //would anyone know how to sort this, tried to put in a bubble sort but i got some many errors i deleted it
    import uuInOut;
    class studentlist
    public static void main(String [] args)
    final int LENGTH = 10; //the length of the list
    //declare variables
    String name, temp3, searchName;
    int age, id, current;
    boolean present = false;
    //create new linked list
    LinkedList list = new LinkedList();
    //open data
    uuTextFile data = new uuTextFile("data.txt");
    data.OpenInputFile();
    //add data from data file to the linked list
    while (!data.EOF)
    name = data.ReadString();//read name
    age = data.ReadInt();//read age
    id = data.ReadInt();//read id
    //new instance of studentrecord to add to list
    StudentRecord temp = new StudentRecord(name, age, id);
    list.insert(0, temp);//add to list
    //Print The whole list
    for (int x = 0; x < list.length(); x ++)
    StudentRecord temp2 = (StudentRecord)list.elementAt(x);
    temp2.printdetails();
    System.out.println("First in list: ");
    StudentRecord First = (StudentRecord)list.getHead().getElement();
    First.printdetails();//print the first entered in the list
    System.out.println("Last in List: ");
    int x = list.length() - 1;
    StudentRecord Last = (StudentRecord)list.elementAt(x);
    Last.printdetails();//print the last entered in the list
    System.out.println("Please Enter Current Position: ");
    current = uuInOut.ReadInt();
    StudentRecord next = (StudentRecord) list.elementAt(current + 1);
    next.printdetails();//prints the next position in the list
    System.out.println("Please Enter Name: ");
    temp3 = uuInOut.ReadString();//reads in a name to search for in the list
    //loop to search through the list for the name entered
    for (int j = 0; j < list.length(); j++){
    StudentRecord temp4 = (StudentRecord)list.elementAt(j);
    searchName = temp4.getname();
    if (temp3.equals(searchName))
    present = true;
    System.out.println(present);
    if (present == true)
    System.out.println("Student Name Found");
    else System.out.println("Not in list" );
    }

    You could scrap this implementation and use a Collection class, then use Collections.sort. Or you could have your implementation implement the List interface and use Collections.sort. But more than likely you are supposed to do this for homework, so in that case I would try to implement the bubble sort and fix it until you don't get any errors. There are other sort routines you could use, but they are all more complicated than the bubble sort, so you will likely get many errors doing that too.
    Good luck
    Lee

  • Bubble Sort in Linked List

    so, everything works through the first iteration (don't know if this is an appropriate term for linked lists, but we just learned arrays) but then it stops. I thought that telling it to continue until position.next != null and increasing the position after every iteration would work but I think I have coded something incorrectly / am not taking something into consideration. I would be greatly obliged if you can offer any advice!
    Thanks,
    Hunter
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
                        previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
                                  previous = a;
                                  a = temp;
                    else
                                  a = a.next;
                      current = current.next;
                                  previous = previous.next;
                 position = position.next;
             head = head.next;

    First, thanks for the response! I have been trying println statements and really don't understand the problem. I have also gone through line-by-line and drawn out what I think is supposed to happen and still can't seem to fully figure out what I am doing wrong. Here is the full code, this might help with the 'definition of my list'.
        public class LinkedList
          public Node head;
           public LinkedList(int length)
             head = null;
             for (int i = 0; i < length; i ++)
                insert(i);
           public LinkedList()
             head = null;
           public void clear()
             head = null;
           public void insert(int n)
             Node current = new Node(n);
             current.next = head;
             head = current;
           public void insert(Node n, int index)
             Node previous, current;
             Node nnode = new Node(-10);
             nnode.next = head;
             previous = nnode;
             current = head;
             while (current != null && index > 0)
                current = current.next;
                previous = previous.next;
                index --;
             if (previous == nnode)
                n.next = head;
                head = n;
             else
                previous.next = n;
                n.next = current;
       //Delete the node at the zero-based index.
           public void delete(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 1; current --)
                currentnode = currentnode.next;
             if (currentnode == head)
                head = head.next;
             else
                currentnode.next = currentnode.next.next;
           public Node getNode(int index)
             Node nnode = new Node(-10);
             nnode.next = head;
             Node current = head;
             while(current.next != null && index > 0)
             {     current = current.next;
                index --;
             return current;
           public int getVal(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 0; current --)
                currentnode = currentnode.next;
          //currentnode should point to the node whose value we want.
             return currentnode.getVal();
           public void print()
             System.out.println();
             head.print();
           private void swap(Node pa, Node a, Node pb, Node b)
             Node temp = b.next;
             pa.next = b;
             if (a.next != b)
                b.next = a.next;
                pb.next = a;
             else
                b.next = a;
             a.next = temp;
           public void selectionSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next  != null)
                current = previous = position.next;
                a = position.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      current = a;
                      while(previous.next != current)
                         previous = previous.next;
                   a = a.next;
                if (current != previous)
                   Node t = position.next;
                   swap(position, t, previous, current);
             //System.out.println("****************");
             //head.print();
                position = position.next;
             head = head.next; //to lose the initial node.
          //System.out.println("end of sorting, head.print is");
          //head.print();
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
              previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
         previous = a;
         a = temp;
                    else
                    a = a.next;
                    current = current.next;
         previous = previous.next;
                 position = position.next;
             head = head.next;
          }

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

  • Help PLEASE with linked list. Inserting a string in the middle of

    I'm trying to insert new strings to a linked list but it seem i cant never insert. the following code has the instructions. What i'm I not doing right? If i try to use the code, the new strings don't go through
    please help someone
    // This method should insert a new node containing the string newString immediately after the first
        // occurrence of the string aString in the list. If aString is not in the list, the method should add a node
        // containing newString to the tail of the list.
        public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
        }

    I have to agree with flounder, go grab a pen and paper and logically work thru the code snippet you posted.
    public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
    }Given a linked list [A-E] we have: A => B => C => D => E. Each Node is referencing the node to it's right, so A references B, D references E etc.
    For example take aString = "A" and newString = "AB". Your code suggests the following:
    1. Create new_node "AB"
    2. if head[A] equals aString[A], TRUE
    2.a head = new_ node
    Now the resulting linkedlist is the following:
    AB => Null
    what happened to the rest of the list?
    Now we go on to your updated example, we result in the following list:
    A => AB => Null
    hmm do you see a pattern here? when inserting a new node we are disregarding any reference to the tail of the list.
    Extending on that idea we have the following pseudo code
    1. if node to be inserted
    1.a new_node.next = list_tail
    1.b current_node.next = new_node
    A => B => C => D => E, where newnode=AA
    AA => B => C => D => E //using 1.a
    A => AA => B => C => D => E //using 1.b
    Mel

  • Inserting integers in a Linked list/List in Java

    Please solve the following problem using Java.
    Problem: Write a program that inserts 25 random integers from 0 to 100 in order in a linked list object. The program should calculate the sum of the elements and the floating-point average of the elements.
    Thanks
    Ripon

    do the following 25 times
    . insert random value between x and y into my list
    All you have to do is replace x and y with your values and compile using the java -idiot option.

  • Inserting into a linked list

    Hello all,
    I'm currently studying for a midterm on linked lists and I'm having a little trouble inserting in "order". What I'm trying to do is use a compareTo method to compare serial numbers of items. The compareTo methos is as follows:
    public int compareTo(Object obj) {
         StoreItem other = (StoreItem) obj;
         return serialNumber - other.serialNumber;
    And the following is my addItem method....which should simply insert the Node into the list in it's proper place according to it's serial number. Any help would be greatly appreciated:)
    public boolean addItem(StoreItem item){
    if (item == null)
    return false;
    else if (first == null)
    {first = new Node (item, null);
                return true;}
    else {
    Node p = first;
    while (p.next != null && item.compareTo(p.value) > 0){
         p = p.next;
    p.next = new Node (item, p.next);
    return true;
    Thanks again!
    Tyler

    My error lies in the "else {" section of the code....The code up to there works fine as I've tried adding one element to an empty list and print it and it works. What doesn't work is when there's already one item in my list and I want to add another, which is what the following code was meant to do:
    else {
    Node p = first;
    while (p.next != null && item.compareTo(p.value) > 0){
         p = p.next;
    p.next = new Node (item, p.next);
    return true;
    This code compiles and doesn't give me a runtime error, yet when I execute the program, it only seems to add the first element....
    Thanks again for the help:)
    Tyler

Maybe you are looking for

  • An error has occurred after upgrading from MBAM 1.0 to 2.0

    The upgrade went fine, uninstalled MBAM v1.0 from SQL and IIS servers, rebooted servers and re-installed with MBAM v2.0.  However, now when I go to the webportal every page shows the "An error has occurred" message.  I've checked the webconfig files

  • How do I delete an item in the sidebar - iPhoto 11

    How do I delete an item on the iPhoto 11 sidebar?

  • Reading swf files

    Hi, I am fairly new to flash. I have done a little test site (not yet published) for a client. I want to send him the swf file so he can get an idea of the site. Does he need to download flashplayer to view the site? Is there another way to send the

  • Need to arrange an appointment with Openreach

    After a long series of very complicated and frustrated problems I'm finally at the point where there is a recognised fault on my line. The fault report said that an engineer would have this resolved by the 18th (with the original report being from th

  • Can't export clips or sequences to Audition from Premiere Pro cc 2014.2

    I can't get audio tracks or anything to export to audition. If I right click on them the option is grayed out and if I go to the clip menu and select "edit in adobe audition" the "clip" is grayed out and if I choose sequence it opens a dialog box tha