解法一:
//时间复杂度O(n^2), 空间复杂度O(n)
/**
* 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) {
ListNode* list = new ListNode(-1);
list->next = head;
ListNode *p1, *p2 = head;
while(p2 && p2->next) {
p1 = list;
ListNode *temp = p2->next->next;
while(p1 && p1->next && p2 && p2->next && p1 != p2) {
if(p1->next->val < p2->next->val) p1 = p1->next;
else {
p2->next->next = p1->next;
p1->next = p2->next;
p2->next = temp;
break;
}
}
if(p1 == p2) p2 = p2->next;
}
return list->next;
}
};
解法一:
此题不难,与数组的插入排序思路完全相同,区别在于链表需要处理边界情况及交换指针。
2019/12/23 23:55