您的位置:首页 > 其它

LeetCode - Insertion Sort List

2014-01-14 22:13 281 查看
Insertion Sort List

2014.1.14 21:58

Sort a linked list using insertion sort.

Solution:

  Everyone must've have learned about insertion sort on some data structure textbooks, like "Data Structures & Algorithm Analysis". They usually present you with source code for insertion sort on arrays. In this problem, you're required to sort a linked list in a similar manner.

  For each list node, use linear search to find the position where it should be inserted. Some boundary conditions need extra code to process, do it carefully.

  Time complexity is O(n^2), space complexity is O(1).

Accepted code:

class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(nullptr == head){
return head;
}
ListNode *ptr, *root;
ListNode *p1, *p2;

root = head;
head = head->next;
root->next = nullptr;
while(head != nullptr){
p1 = head->next;
ptr = root;
if(head->val <= root->val){
head->next = root;
root = head;
}else{
while(ptr->next != nullptr){
if(head->val >= ptr->val && head->val <= ptr->next->val){
break;
}else{
ptr = ptr->next;
}
}
p2 = ptr->next;
ptr->next = head;
head->next = p2;
}
head = p1;
}

// 1WA here, not head = root->next;
head = root;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: