[leetcode]Insertion Sort List
2014-04-11 14:56
330 查看
/** * 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 there is only one node or null, return immediately if(head==NULL || head->next == NULL) return head; // insert each node from second node to the front part ListNode * current = head->next; head->next = NULL; while(current) { ListNode * temp = head; ListNode * prev = NULL; // to keep the next node of current node to be inserted, important!!! ListNode * next = current->next; while(temp){ if(current->val > temp->val) { // do not find the right place to insert prev = temp; temp = temp->next; } else { // find the right place to insert if(prev == NULL){ // if it is the head node current->next = head; head = current; } else { current->next = temp; prev->next = current; } break; } } // if it is the end node if(!temp) { prev->next = current; current->next = NULL; } current = next; } return head; } };
相关文章推荐
- [Leetcode Solution]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-147
- leetcode 刷题之路 27 Insertion Sort List
- LeetCode - Insertion Sort List
- LeetCode 147 Insertion Sort List
- leetcode 147 Insertion Sort List java 算法
- leetcode:Insertion Sort List
- Leetcode_insertion-sort-list
- [leetcode 147]Insertion Sort List
- Leetcode:insertion-sort-list
- 【LeetCode with Python】 Insertion Sort List
- LeetCode:Insertion Sort List
- leetcode之insertion Sort list
- [LeetCode 148] Insertion Sort List
- leetcode 133: Insertion Sort List