方法一:
/**
* 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* dummy=new ListNode(-1);
while(head){
ListNode* p=dummy;
ListNode* newhead=head->next;
while(p->next && head->val > p->next->val)
p=p->next;
head->next=p->next;
p->next=head;
head=newhead;
}
return dummy->next;
}
};
方法二:递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private:
ListNode* insert(ListNode* head, ListNode* node) {
if(!head || head->val > node->val) {
node->next = head;
return node;
}
head->next = insert(head->next, node);
return head;
}
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* res = NULL;
ListNode* p = head;
while(p) {
ListNode* next = p->next;
res=insert(res, p);
p = next;
}
return res;
}
};