题解 | 链表分割

链表分割

https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
  public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        if (!pHead || !pHead->next) return pHead;
        ListNode dummySmall(0);
        ListNode dummyLarge(0);

        ListNode* pSmall = &dummySmall;
        ListNode* pLarge = &dummyLarge;
 
        while (pHead) {
            if (pHead->val < x) {
                pSmall->next = pHead;
                pSmall = pSmall->next;
            } else {
                pLarge->next = pHead;
                pLarge = pLarge->next;
            }
            pHead = pHead->next;
        }
        pLarge->next = nullptr;
        pSmall->next = dummyLarge.next;
        return dummySmall.next;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务