题解 | #链表分割#

链表分割

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
        //用两个哨兵位来搞
        ListNode* tmp_little = (ListNode*)malloc(sizeof(ListNode));
        tmp_little->next = NULL;
        ListNode* tail_little = tmp_little;
        ListNode* tmp_big = (ListNode*)malloc(sizeof(ListNode));
        tmp_big->next = NULL;
        ListNode* tail_big = tmp_big;
        ListNode* cur = pHead;
        while(cur)
        {
            if(cur->val<x)
            {
                tail_little->next = cur;
                tail_little = cur;
            }
            else{
                tail_big->next = cur;
                tail_big = cur;
            }
            cur = cur->next;
        }
        tail_little->next = NULL;
        tail_big->next = NULL;
        tail_little->next = tmp_big->next;
        return tmp_little->next;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务