题解 | #链表分割#

链表分割

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
        struct ListNode* cur, *lesshead, *lesstail, *greaterhead, *greatertail;
        cur = phead;
        lesshead = (struct ListNode*)malloc(sizeof(ListNode));
        greaterhead = (struct ListNode*)malloc(sizeof(ListNode));
        lesstail = lesshead;
        greatertail = greaterhead;
        while(cur)
        {
            if(cur->val < x)
            {
                lesstail->next = cur;
                lesstail = lesstail->next;
            }
            else {
                greatertail->next = cur;
                greatertail = greatertail->next;
            }
            cur = cur->next;
        }
        lesstail->next = greaterhead->next;
        greatertail->next = NULL;
        phead = lesshead->next;
        free(lesshead);
        free(greaterhead);
        return phead;
    }
};

全部评论

相关推荐

09-12 11:55
已编辑
湖南工商大学 Java
那一天的Java_J...:这种一堆问题的,别去
点赞 评论 收藏
分享
09-18 20:41
门头沟学院 Java
要个offer怎么这...:哈哈哈哈哈哈,我也拿了0x10000000个offer,秋招温啦啦啦,好开心
我的秋招日记
点赞 评论 收藏
分享
一天代码十万三:这个学历有中大厂实习也是0面,没办法,斩杀线是这样的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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