【leetcode】链表分割-方法1. 不用哨兵位

时间:2024-03-01 12:09:21
#include <csignal>
class Partition {
  public:
    ListNode* partition(ListNode* pHead, int x) {
        ListNode* list1 = nullptr;
        ListNode* i1 = nullptr;
        ListNode* list2 = nullptr;
        ListNode* i2 = nullptr;
        ListNode* cur = pHead;

        while (cur) {
            if (cur->val < x) {
                if (i1 == nullptr) {
                    i1 = list1 = cur;
                } else {
                    i1->next = cur;
                    i1 = i1->next;
                }
            } else {
                if (i2 == nullptr) {
                    i2 = list2 = cur;
                } else {
                    i2->next = cur;
                    i2 = i2->next;
                }
            }
            cur = cur->next;
        }
        if(list1==nullptr&&list2==nullptr)
            return nullptr;
        if(list1==nullptr&&list2!=nullptr)
            return list2;

        i1->next=list2;
        if(list2==nullptr)
            return list1;
        i2->next=nullptr;
        return list1;
    }
};

2