题目链接:https://leetcode-cn.com/problems/insertion-sort-list/
题目如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode* dummy=new ListNode(INT_MIN);
ListNode* p=head;
while(p!=NULL){
ListNode* temp=p->next;
ListNode* q=dummy;//每次从dummy开始查找,防止头节点可能发生变动
while(q->next!=NULL && q->next->val <= p->val){
q=q->next;
}
//将p节点插入q->next的位置
p->next=q->next;
q->next=p;
p=temp;
}
return dummy->next;
}
};