leetcode 86 Partition List

1. 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head||!head->next) return head;
        ListNode ln(-1);ln.next=head;
        ListNode* pre=&ln,*cur=head,*node=pre;
        while(cur) {
            if(cur->val>=x) {
                while(cur&&cur->val>=x) {
                    node=cur;
                    cur=cur->next;
                }
                if(!cur) break;
                node->next=cur->next;
                cur->next=pre->next;
                pre->next=cur;
                pre=cur;
                cur=node->next;
            }
            else {
                if(pre->next!=cur) {
                    node->next=cur->next;
                    cur->next=pre->next;
                    pre->next=cur;
                    pre=cur;
                    cur=node->next;
                }
                else {
                    pre=cur;
                    cur=cur->next;
                }
            }
            
        }
        return ln.next;
    }
};

2. 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode less(0),more(0);
        ListNode* cur=head,*lessp=&less,*morep=&more;
        while(cur) {
            if(cur->val<x) {
                lessp->next=cur;
                lessp=lessp->next;
            }
            else {
                morep->next=cur;
                morep=morep->next;
            }
            cur=cur->next;
        }
        morep->next=nullptr;
        lessp->next=more.next;
        return less.next;
    }
};

 

Guess you like

Origin www.cnblogs.com/LiuQiujie/p/12617689.html