取巧(作弊)做法:
/**
* 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) {
vector<int> hh;
ListNode* iter = head;
while(iter)
{
hh.push_back(iter->val);
iter = iter->next;
}
sort(hh.begin(), hh.end());
iter = head;
int i = 0;
while(iter)
{
iter->val = hh[i];
iter = iter->next;
i++;
}
return 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) {
ListNode* dummyHead = new ListNode(0);
ListNode* pre = dummyHead;; //插入位置的前一个节点
ListNode* cur = head;
ListNode* rear; //待排序节点的下一个节点
while(cur != NULL){
rear = cur->next;
while(pre->next != NULL && pre->next->val < cur->val){
pre = pre->next;
}
cur->next = pre->next;
pre->next = cur;
cur = rear;
pre = dummyHead;
}
return dummyHead->next;
}
};