题解 | #链表分割#

链表分割

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) 
    {
        struct ListNode* newhead, *newtail,*oldhead, *oldtail;
        newhead = newtail = (struct ListNode*)malloc(sizeof(struct ListNode));
        oldhead = oldtail = (struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* cur = pHead;

        while(cur)
        {
            if(cur->val < x)
            {
                newtail->next = cur;
                newtail = cur;
                cur = cur->next;
            }
            else 
            {
                oldtail->next = cur;
                oldtail = cur;
                cur = cur->next;
            }

        }

        newtail->next = oldhead->next;
        oldtail->next = NULL;

        return newhead->next;
    }
};











全部评论

相关推荐

04-17 10:16
门头沟学院 Java
不河狸啊:为什么我的是已送达,连已读都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务