插入排序的意思是每次从待排序数列中选出一个,插入到已排序的数列中。
/** 这个是一开始的答案,但是案例没有全部通过,检查发现是注释处修改了head指针所致。
* 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 tony(0);
ListNode* p = NULL, *q = NULL;
while (head) {
p = &tony;
q = p->next;
while (q && q->val val) {
p = p->next;
q = q->next;
}
p->next = head;
p->next->next = q;
head = head->next;
}
return tony.next;
}
};
正确答案
/**
* 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 tony(0);
ListNode* p = NULL, *q = NULL, *t = NULL;
while (head) {
p = &tony;
q = p->next;
t = head;
head = head->next;
while (q && q->val val) {
p = p->next;
q = q->next;
}
t->next = q;
p->next = t;
}
return tony.next;
}
};