Insertion sort list (single-linked list insertion sort)

Source: Internet
Author: User

Source: Https://leetcode.com/problems/insertion-sort-list

Sort a linked list using insertion sort.

Method:

1. Use a prehead to point to the head node so that no special processing is required when inserting a node in front of the head node (that is, a node value is smaller than the head node)

2. Start the traversal from the head node, if the value of the next node of the current node is larger than the value of the current node, walk from the beginning to find the first node that is larger than the value of the next node of the current node and insert it in front of it, noting that the insertion requires simultaneous handling of the node's position and insertion position.

Time complexity, average O (n^2), preferably O (1), at which point the node itself is ordered, the worst O (n^2)

Space complexity, required auxiliary storage for O (1)

Stability, stability, elements with the same value are kept in relative order after sorting

1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7  * }8  */9 classSolution {Ten      PublicListNode insertionsortlist (ListNode head) { OneListNode Prehead =NewListNode (0); AListNode next =NULL, node =NULL, Tmpnode =NULL; -Prehead.next =head; -          while(Head! =NULL) { theNext =Head.next; -             if(Next! =NULL&& Next.val <head.val) { -node =Prehead; -                  while(Node.next! =NULL&& Node.next.val <=next.val) { +node =Node.next; -                 } +Tmpnode =Node.next; ANode.next =Next; atHead.next =Next.next; -Next.next =Tmpnode; -}Else { -Head =Head.next; -             } -         } in         returnPrehead.next; -     } to}//8 Ms

Insertion sort list (single-linked list insertion sort)

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.