Sort a linked list using insertion sort.

插入排序:每一趟将一个待排序的记录,按照其关键字的大小插入到有序队列的合适位置里,知道全部插入完成。 

在讲解直接插入排序之前,先让我们脑补一下我们打牌的过程。

先拿一张5在手里,

再摸到一张4,比5小,插到5前面,

摸到一张6,嗯,比5大,插到5后面,

摸到一张8,比6大,插到6后面,

以上的过程,其实就是典型的直接插入排序,每次将一个新数据插入到有序队列中的合适位置里

/**
  * Definition for singly-linked list.
  * public class ListNode {
  *     int val;
  *     ListNode next;
  *     ListNode(int x) {
  *         val = x;
  *         next = null;
  *     }
  * }
  */
public class Solution {
     public ListNode insertionSortList(ListNode head) {
         if (head ==  null ){
             return null ;
         }
         ListNode curNode = head.next;
         ListNode pNode =  new ListNode( 0 );
         pNode.next = head;
         head.next =  null ;
         while (curNode !=  null ){
             ListNode compareNode = pNode;
             while (compareNode !=  null ){
                 if (compareNode.next ==  null || compareNode.next.val>= curNode.val){
                     break ;
                 }
                 compareNode = compareNode.next;
             }
             ListNode temp = curNode.next;
             curNode.next = compareNode.next;
             compareNode.next = curNode;
             curNode = temp;
         }
         return pNode.next;
     }
}

猜你喜欢

转载自blog.csdn.net/boguesfei/article/details/80427230