Description
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null , return 0->1->2->3->null .
Problem solving: The list is sorted by inserting. A very simple topic, but there are still a lot of problems.
Summarize the problems encountered:
(1) Without a head node, in order to facilitate the construction of a, return to the first node of the next on the line.
(2) There is no need to always in the original linked list of tangled, can apply for a head node, the original linked list of points inserted into each.
(3) There is no need to consider how to write more simple, can make is the most important, write a method can be re-optimized.
(4) After a number of test data has not passed, to consider the feasibility of the algorithm, do not climb out in a pit.
The code is as follows:
1 /**2 * Definition for ListNode3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A - Public classSolution { - /** the * @paramhead:the first node of linked list. - * @return: The head of linked list. - */ - PublicListNode insertionsortlist (ListNode head) { + //Write your code here - //the head node of the new linked list +ListNode dummy =NewListNode (0); A while(Head! =NULL){ atListNode node =dummy; - while(Node.next! =NULL&& Node.next.val <head.val) { -node =Node.next; - } -ListNode temp =Head.next; -Head.next =Node.next; inNode.next =head; -Head =temp; to } + returnDummy.next; - } the}
173. Insertion Sort List "Lintcode by Java"