Insertion Sort List

考察插入排序的概念。
思路:对于每一个带插入的节点要在以排序的节点中找到插入的位置。
   每次都要从头遍历已经排序好的节点,需要将以排序好的节点与未排序好的节点断开。
/*
Sort a linked list using insertion sort. */ /** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @return: The head of linked list. */ public ListNode insertionSortList(ListNode head) { if (head == null) { return head; } ListNode dummy = new ListNode(0);
     // 这里不能直接连接head
     // 保证已经排序好的节点与未排序好的节点是断开的。
while (head != null) { ListNode node = dummy; while (node.next != null && node.next.val < head.val) { node = node.next; } ListNode tmp = head.next; head.next = node.next; node.next = head; head = tmp; } return dummy.next; } }

 

posted @ 2016-03-09 08:16  YuriFLAG  阅读(182)  评论(0)    收藏  举报