0
0

89. Partition List

Posted at

solution

before linked listとafter linked listを用意しておいて、x未満のやつはbeforeに連ねていって、x以上のやつはafterに連ねていく。
時間計算量はO(N)
空間計算量はO(1) 使っているのはポインタのための変数だけ。

/**
 * 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* partition(ListNode* head, int x) {
        ListNode* before_head = new ListNode(0);
        ListNode* before = before_head;
        ListNode* after_head = new ListNode(0);
        ListNode* after = after_head;

        while(head != nullptr){
            if(head->val < x){
                before->next = head;
                before = before->next;
            } else{
                after->next = head;
                after = after->next;
            }
            head = head->next;
        }
        after->next = nullptr;
        before->next = after_head->next;
        return before_head->next;
    }
};

最初にやろうとした方針

/**
 * 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* partition(ListNode* head, int x) {
        ListNode nil = ListNode();
        nil.next = head;
        ListNode* prev = &nil;
        ListNode* prevLeft = &nil;
        ListNode* next = &nil;

        while (head != nullptr){
            next = head->next;
            if (head->val < x){
                prev->next = head->next;
                head->next = prevLeft->next;
                prevLeft->next = head;
                prevLeft = head;
            } else{
                prev = head;
            }
            head = next;
        }
        return nil.next;
    }
};

これだと[1,1]でx=2とかの時に失敗する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0