173. Insertion Sort List "Lintcode by Java"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.