LeetCode: Insertion Sort List
来源:互联网 发布:投影机的网络接口 编辑:程序博客网 时间:2024/05/16 08:35
Sort a linked list using insertion sort.
/** * 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) { if(head == NULL || head->next == NULL) return head;ListNode* cur = head->next; ListNode* itr = head; ListNode* pre = head;itr->next = NULL; while(cur) {itr = head;ListNode* next = cur->next;if(cur->val < itr->val){cur->next = itr;head = cur;}else{while(itr != NULL){if(cur->val >= itr->val){if(itr->next == NULL){itr->next = cur;cur->next = NULL;break;}else{pre = itr;itr = itr->next;}}else{pre->next = cur;cur->next = itr;break;}}}cur = next; } return head; }};
Round 2:
class Solution {public: ListNode *insertionSortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *right = head->next; head->next = NULL; while(right != NULL) { ListNode *left = head; ListNode *pre = NULL; ListNode *next = right->next; while(left != NULL && right->val > left->val) { pre = left; left = left->next; } if(pre == NULL) { right->next = left; head = right; } else { pre->next = right; right->next = left; } right = next; } return head; }};
Round 3:
/** * 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) { if(NULL == head || NULL == head->next) return head; ListNode *right = head->next, *pre = NULL, *left = head; head->next = NULL; while(NULL != right) { ListNode *next = right->next; if(right->val <= head->val) { right->next = head; head = right; } else { ListNode *left = head; while(NULL != left && right->val > left->val) { pre = left; left = left->next; } if(left == NULL) { pre->next = right; right->next = NULL; } else { pre->next = right; right->next = left; } } right = next; } return head; }};
0 0
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List (LeetCode)
- [LeetCode] Insertion Sort List
- [LeetCode]Insertion Sort List
- leetcode Insertion Sort List
- Insertion Sort List -- LeetCode
- Insertion Sort List (LeetCode)
- LeetCode Insertion Sort List
- leetcode Insertion Sort List
- ThinkPHP查询返回简单字段数组
- hbase性能优化大全,很全,很牛
- bash_profile,bashrc,profile等区别
- 【算法导论】第三版课后习题*2.3-7
- java 中 byte Ascii Hex int short 字串之间的互转
- LeetCode: Insertion Sort List
- 数据库设计1
- 什么ppt转换成pdf转换器好
- win8.1中xshell输入中文显示问号问题
- IE 扩展调用主窗口中的函数
- Android反编译(图文)
- 如何修改WAMP中mysql默认空密码&重新登录phpmyadmin
- 检测浏览器版本包括IE11
- 通过DNS隧道来控制Meterpreter