题解 | #链表分割#

链表分割

http://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) { //创建哨兵位 方便尾插 ListNode* less_head, *greater_head, less_tail, greater_tail; less_head = less_tail = (ListNode)malloc(sizeof(ListNode)); greater_head = greater_tail = (ListNode)malloc(sizeof(ListNode)); less_tail->next = NULL; greater_tail->next = NULL;

    ListNode* cur = pHead;
    while(cur)
    {
        if(cur->val < x)
        {
            less_tail->next = cur;
            less_tail = less_tail->next;
        }
        else
        {
            greater_tail->next = cur;
            greater_tail = greater_tail->next;
        }
        cur = cur->next;
    }
    //链接两个链表
    less_tail->next = greater_head->next;
    //关键点 防止成环
    greater_tail->next = NULL;
    //给头节点
    pHead = less_head->next;
    //释放空间
    free(less_head);
    free(greater_head);
    return pHead;
}

};

全部评论

相关推荐

07-18 18:45
已编辑
中山职业技术学院 Java
投递TP-LINK等公司7个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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