[leetcode][list][sort] Insertion Sort List
2015-05-22 18:13
204 查看
题目;
Sort a linked list using insertion sort.
88ms
优化:28ms
Sort a linked list using insertion sort.
88ms
/** * 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 *p = head->next;//用于遍历原链表 head->next = NULL;//head是新链表的第一个也是最后一个节点,记得next置NULL while(p){ ListNode *pNext = p->next;//先暂存p的后继节点 ListNode *pCur = head;//用于遍历新链表 ListNode *pre = NULL;//当前节点的前驱 while(pCur && pCur->val < p->val) {//查找p的插入位置 pre = pCur; pCur = pCur->next; } if(NULL == pre){//成为新链表的第一个节点 p->next = head; head = p; } else{//插入位置是pre和pCur之间 pre->next = p; p->next = pCur; } p = pNext;//更新遍历指针 } return head; } };
优化:28ms
/** * 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 *p = head->next, *tail = head;//taile指向新链表的最后一个节点 while (p != NULL){ ListNode *pNext = p->next; if (p->val < head->val){//比最小的小 p->next = head; head = p; } else if (tail->val <= p->val){//比最大的大 tail->next = p; tail = p; } else{//在中间 ListNode *q = head->next, *pre = head; while (q->val < p->val){ pre = q; q = q->next; } pre->next = p; p->next = q; } p = pNext; } tail->next = NULL; return head; } };
相关文章推荐
- 59_leetcode_Insertion Sort List
- LeetCode——Insertion Sort List
- 【LeetCode with Python】 Insertion Sort List
- LeetCode:Insertion Sort List
- leetcode之insertion Sort list
- leetcode 133: Insertion Sort List
- (leetcode)Insertion Sort List
- leetcode_c++:链表:Insertion Sort List(147)
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- LeetCode147—Insertion Sort List
- Insertion Sort List (LeetCode)
- [Leetcode Solution]Insertion Sort List
- leetcode[147]Insertion Sort List
- [Leetcode] Insertion Sort List
- LeetCode (Insertion Sort List)
- Insertion Sort List 【leetcode】
- leetcode Insertion Sort List(*)
- [leetcode 147] Insertion Sort List
- leetcode-Insertion Sort List-147
- 【LeetCode】Insertion Sort List