ListNode* insertionSortList(ListNode* head) {
     if (!head || !head->next) return head;
     
     ListNode fakeHead(INT_MIN);
     fakeHead.next = head;
     auto curr = head->next;
     head->next = nullptr;
     
     while(curr) {
         auto prev = &fakeHead, next = curr->next, sorted = fakeHead.next;
         while (prev) {
             if (!sorted) {
                 prev->next = curr;
                 curr->next = nullptr;
                 break;
             }
             
             if (prev->val <= curr->val && curr->val < sorted->val) {
                 prev->next = curr;
                 curr->next = sorted;
                 break;
             } else {
                 prev = sorted;
                 sorted = sorted->next;
             }
         }
         curr = next;
     }
     return fakeHead.next;
 }
Exemple #2
0
ListNode *partition(ListNode *head, int x) {
    ListNode fakeHead(0);
    fakeHead.next = head;
    head = &fakeHead;
    
    ListNode *pos = NULL;
    for(ListNode *p = head; p!=NULL && p->next!=NULL; ){
        if (!pos && p->next->val >= x){
            pos = p;
            p=p->next;
            continue;
        }
        if (pos && p->next->val < x){
            ListNode *pNext = p->next;
            p->next = pNext->next;
            pNext->next = pos->next;
            pos->next = pNext;
            pos = pNext;
            continue;
        }
        p=p->next;
    }
    
    return head->next;
}
 ListNode *removeNthFromEnd(ListNode *head, int n) {
     if (head==NULL || n<=0){
         return NULL;
     }
     ListNode fakeHead(0);
     fakeHead.next=head;
     head=&fakeHead;
     
     ListNode *p1, *p2;
     p1=p2=head;
     for(int i=0; i<n; i++){
         if (p2==NULL) return NULL;
         p2=p2->next;
     }
     while (p2->next!=NULL){
         p2=p2->next;
         p1=p1->next;
     }
     
     p1->next = p1->next->next;
     return head->next;
 }
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode fakeHead(-1);
        fakeHead.next = head;

        ListNode *pre = &fakeHead;
        while(head) {
            ListNode *next = head->next;
            if (next == NULL || next->val != head->val) {
                pre = head;
                head = head->next;
                continue;
            }
            
            while (next != NULL && next->val == head->val) {
                head->next = next->next;
                delete next;
                next = head->next;
            }
            pre->next = head->next;
            delete head;
            head = pre->next;
        }
        return fakeHead.next;
    }