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 ;}};