LeetCode -- Insertion Sort List

Source: Internet
Author: User

LeetCode -- Insertion Sort List
Description:
Sort a linked list using insertion sort.


Ideas:
Insert a sort list class, add the records to the list one by one, and use the list to create a new linked list.




Implementation Code:



/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode InsertionSortList(ListNode head) {        if(head == null || head.next == null){    return head;    }    var list = new SortedNodes();    while(head != null){    list.Add(head.val);    head = head.next;    }        ListNode h = null;    ListNode node = null;    var c = 0;    foreach(var n in list.Nodes){    if(c == 0){    node = new ListNode(n);    h = node;    }else{    node.next = new ListNode(n);    node = node.next;    }        c++;    }    return h;    }public class SortedNodes{private IList
 
   _nodes;public SortedNodes(){_nodes = new List
  
   ();}public void Add(int n){for(var i = 0;i < _nodes.Count; i++){if(n < _nodes[i]){_nodes.Insert(i,n);return;}}_nodes.Add(n);}public IList
   
     Nodes{get{return _nodes;}}}}
   
  
 


 

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.