首页 > 代码库 > 【Leetcode】Insertion Sort List
【Leetcode】Insertion Sort List
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) { //链表不能从后往前扫描,所以每次从头往后扫描? //有没有更好的解决方案,细节的提升, 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; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。