简体   繁体   中英

Insertion Sort For Singly Linked List Java

I'm trying to make an Insertion Sort for a Linked List class to sort in ascending. I'm not really sure what I need to do. I can't find a way to go back to the beginning of the list.

public static void LLInsertionSort (LinkedList LL){

    IntNode currentNode = head;
    IntNode tail = null;
    while(currentNode != null&& tail != head ){


         while (currentNode.getData() > currentNode.getNext().getData()){

             int temp = currentNode.getData();
             currentNode.setData(currentNode.getNext().getData());
             currentNode.getNext().setData(temp);

You need to start each time from the first Node in your list .

public static IntList LLInsertionSort(Node head)
{
   IntNode current = head;
   IntNode tail = null;
   while(current != null&& tail != head )
   {
      IntNode next = current;
      for( ; next.next != tail;  next = next.next)
      {
        if(next.value <= next.next.value)
        {
          int temp = next.value;
          next.value = next.next.value;
          next.next.value = temp;
        }
      }
      tail = next;
      current = head;
   }
   return this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM