题目:Sort a linked list using insertion sort
代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(1)
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head) return head;
ListNode dummy{-1};
dummy.next = head;
ListNode* p = head;
while (p -> next) {
ListNode *node = &dummy
int tmp = p -> next -> val;
while (node != p) {
if (tmp < node -> next -> val) {
ListNode* p1 = node -> next;
ListNode* p2 = p -> next;
p -> next = p2 -> next;
node -> next = p2;
p2 -> next = p1;
break;
}
node = node -> next;
}
if (node == p) p = p -> next;
}
return dummy.next;
}
};