147. Insertion Sort List, 147 insertion

Source: Internet
Author: User

147. Insertion Sort List, 147 insertion

Sort a linked list using insertion sort.

 

Use an auxiliary pointer as the header to avoid the boundary situation when the head is changed.

 

1/** 2 * Definition for singly-linked list. 3 * struct ListNode {4 * int val; 5 * ListNode * next; 6 * ListNode (int x): val (x), next (NULL) {} 7 *}; 8 */9 class Solution {10 public: 11 ListNode * insertionSortList (ListNode * head) {12 if (head = NULL) {13 return head; 14} 15 16 ListNode * helper = new ListNode (0); 17 ListNode * pre = helper; 18 ListNode * cur = head; 19 20 while (cur! = NULL) {21 ListNode * next = cur-> next; 22 // save head position 23 pre = helper; 24 while (pre-> next! = NULL & pre-> next-> val <cur-> val) {25 pre = pre-> next; 26} 27 // insert 28 cur-> next = pre-> next; 29 pre-> next = cur; 30 // restore 31 32 cur = next; 33} 34 return helper-> next; 35} 36 };

 

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.