Leetcode 147. Insertion sort List Insert sorting in Java

Source: Internet
Author: User

147. Insertion Sort List
    • Total accepted:80869
    • Total submissions:263074
    • Difficulty:medium

Sort a linked list using insertion sort.

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode insertionsortlist (ListNode head) {if(head==NULL|| head.next==NULL)returnHead; ListNode Newhead=NewListNode (0);//The back uses Tmp.next to compare with the pre, so add a new NewheadListNode cur=Head;  while(cur!=NULL) {ListNode next=cur.next;//put here instead of at the end of the loop to prevent out of indexListNode tmp=Newhead;  while(tmp.next!=NULL&& tmp.next.val<cur.val) {tmp=Tmp.next; } Cur.next=Tmp.next; Tmp.next=cur; Cur=Next; }       returnNewhead.next; }}

  

Leetcode 147. Insertion sort List Insert sorting in 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.