[Leetcode] insertion sort list

Source: Internet
Author: User

Sort a linked list using insertion sort.

 

1st (3 tries)

/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * insertionsortlist (listnode * head) {// The linked list cannot be scanned from the back to the back, so each scan starts from the back to the back? // Is there a better solution and improvement in details? listnode * cur; listnode * pre; If (Head = NULL) return NULL; If (Head-> next = NULL) return head; Pre = head; cur = head-> next; while (cur! = NULL) {// scan from the head if (cur-> Val <pre-> Val) {listnode * innercur = head-> next; listnode * innerpre = head; while (cur-> Val> innercur-> Val) {innercur = innercur-> next; innerpre = innerpre-> next ;} if (innerpre = Head & innerpre-> Val> cur-> Val) {pre-> next = cur-> next; cur-> next = head; head = cur;} else {pre-> next = cur-> next; innerpre-> next = cur; cur-> next = innercur;} cur = pre-> next ;} else {pre = pre-> next; cur = cur-> next ;}} return head ;}};

2nd (5 tries)

/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * insertionsortlist (listnode * head) {// insertion sort mean that element before I must be sorted listnode * newhead = new listnode (int_min ); newhead-> next = head; listnode * SPRE = newhead; listnode * scur = head; // change scur !!! While (scur! = NULL) {listnode * pre = newhead; listnode * cur = newhead-> next; while (cur! = Scur & cur-> Val <= scur-> Val) {pre = pre-> next; cur = cur-> next;} // change if (cur! = Scur) {SPRE-> next = scur-> next; pre-> next = scur; scur-> next = cur; scur = SPRE-> next ;} else {SPRE = SPRE-> next; scur = scur-> next ;}} listnode * ans = newhead-> next; Delete newhead; return ans ;}};

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.