LeetCode (Insertion Sort List)
2017-07-10 15:49
316 查看
Problem:
Sort a linked list using insertion sort.
Solution:
/**
* 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 || !head->next) return head;
ListNode l(0), *pre = &l;
ListNode *cur = head, *next;
while(cur){
next = cur->next;
while(pre->next && pre->next->val < cur->val)
pre = pre->next;
cur->next = pre->next;
pre->next = cur;
cur = next;
pre = &l;
}
return l.next;
}
};
Sort a linked list using insertion sort.
Solution:
/**
* 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 || !head->next) return head;
ListNode l(0), *pre = &l;
ListNode *cur = head, *next;
while(cur){
next = cur->next;
while(pre->next && pre->next->val < cur->val)
pre = pre->next;
cur->next = pre->next;
pre->next = cur;
cur = next;
pre = &l;
}
return l.next;
}
};
相关文章推荐
- 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[AC源码]
- leetcode 147 —— Insertion Sort List
- Insertion Sort List Leetcode java
- [LeetCode] Insertion Sort List 单向链表插入排序
- LeetCode:Insertion Sort List//链表插入排序
- [LeetCode 147] Insertion Sort List
- [LeetCode] Insertion Sort List
- [leetcode] Insertion Sort List
- LeetCode Insertion Sort List 链表插入排序
- Insertion Sort List Leetcode
- LeetCode -- Insertion Sort List
- leetcode[147]:Insertion Sort List
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- leetcode insertionSortList