题解 | #链表分割#

链表分割

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;
    }
};

全部评论

相关推荐

牛客963010790号:为什么还要收藏
点赞 评论 收藏
分享
11-08 10:39
门头沟学院 C++
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务