LeetCode-M-Insertion Sort List
2017-04-07 20:05
344 查看
题意
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* tail = head; ListNode* next = head->next; while(next != NULL){ ListNode* pre = NULL; ListNode* cur = head; while(cur != next && cur->val < next->val){ pre = cur; cur = cur->next; } if(cur == next) { tail = next; }else if(pre == NULL){ tail->next = next->next; next->next = head; head = next; }else{ tail->next = next->next; next->next = pre->next; pre->next = next; } next = tail->next; } return head; } };
相关文章推荐
- 【LeetCode】Insertion Sort List
- Leetcode: Insertion Sort List
- LeetCode(2):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
- LeetCode---Insertion Sort List
- LeetCode - Insertion Sort List
- 【LeetCode】-Insertion Sort List
- LeetCode Insertion Sort List
- leetcode做题总结,题目Insertion Sort List 2013/11/12
- Leetcode习题:Insertion Sort List
- [leetcode 147]Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode---Insertion Sort List