Leetcode-insertion sort list

Source: Internet
Author: User

It is quite a basic problem. however I spent half an hour solving it and made two mistakes. guess it's because I haven't written some fundamental data structures like linked list for a while and kind of get lost. I shoshould practice these questions more.


public class Solution {public ListNode insertionSortList(ListNode head) {if (head == null || head.next == null)return head;ListNode cNode = head.next;ListNode prevcNode = head;while (cNode != null) {if (cNode.val <= head.val) {prevcNode.next = cNode.next;cNode.next = head;head = cNode;cNode = prevcNode.next;}else {ListNode tNode = head;while( tNode.next != cNode &&tNode.next.val < cNode.val){tNode = tNode.next;}if(tNode.next == cNode){prevcNode = cNode;cNode = cNode.next;}else{prevcNode.next = cNode.next;cNode.next = tNode.next;tNode.next = cNode;cNode = prevcNode.next;}}}return head;}}


Leetcode-insertion sort list

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.