Leetcode_insertion-sort-list
2014-04-20 14:47
211 查看
地址:http://oj.leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
思路:模拟题,新建一个虚拟节点指向头节点,用节点tail维护已排序好的链表。
参考代码:
不小心写了个选择排序的
Sort a linked list using insertion sort.
思路:模拟题,新建一个虚拟节点指向头节点,用节点tail维护已排序好的链表。
参考代码:
/** * 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) return head; ListNode* virtual_head = new ListNode(-1<<31), *p = head->next, *cmp = NULL, *nxt = NULL, *tail = head; virtual_head->next = head; while(p) { nxt = p->next; cmp = virtual_head; while(cmp!=tail && cmp->next->val < p->val) cmp = cmp->next; if(cmp != tail) { p->next = cmp->next; cmp->next = p; } else { tail = tail->next = p; } p = nxt; } tail->next = NULL; return virtual_head->next; } };
不小心写了个选择排序的
class Solution { private: ListNode* merge(ListNode*l1, ListNode*l2) { if(!l1) return l2; else if(!l2) return l1; ListNode*head = NULL, *p1 = l1, *p2 = l2, *cur = NULL; while(p1 && p2) { if(p1->val <= p2->val) { if(!head) head = cur = p1; else cur = cur->next = p1; p1 = p1->next; } else { if(!head) head = cur = p2; else cur = cur->next = p2; p2 = p2->next; } } if(p1) cur->next = p1; else cur->next = p2; return head; } void split(ListNode*head, ListNode**l1, ListNode**l2) { ListNode* lnode = *l1, *rnode = *l2; if(!head) lnode = rnode = NULL; else if(!head->next) { lnode = head; rnode = NULL; } else { lnode = rnode = head; ListNode *tmp = NULL; while(lnode) { lnode = lnode->next; if(lnode) { lnode = lnode->next; tmp = rnode; rnode = rnode->next; } } tmp->next = NULL; *l1 = lnode = head; *l2 = rnode; } } public: ListNode *sortList(ListNode *head) { if(!head || !head->next) return head; ListNode*l1 = NULL, *l2 = NULL; split(head, &l1, &l2); l1 = sortList(l1); l2 = sortList(l2); return merge(l1, l2); } };
相关文章推荐
- [LeetCode] Insertion Sort List
- LeetCode: Insertion Sort List [147]
- LeetCode :: Insertion Sort List [具体分析]
- (Leetcode 147)Insertion Sort List
- [leetcode] Insertion Sort List(python)
- Leetcode[147]-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 】 python 实现
- Leetcode: Insertion Sort List
- LeetCode - Insertion Sort List
- [leetcode] Insertion Sort List
- leetcode之Insertion Sort List
- Leetcode 147 Insertion Sort List
- Leetcode: Insertion Sort List