题解 | #链表分割#

链表分割

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) {
        // write code here
        struct ListNode*head1,*head2,*tail1,*tail2;
         head1=tail1=(struct ListNode*)malloc(sizeof(struct ListNode));
         head2=tail2=(struct ListNode*)malloc(sizeof(struct ListNode));
        tail1->next=NULL;
        tail2->next=NULL;
        struct ListNode* cur=pHead;
        while(cur)
        {
            if(cur->val<x)
            {
                tail1->next=cur;
                tail1=tail1->next;
            }else
            {
                tail2->next=cur;
                tail2=tail2->next;
            }
            cur=cur->next;
        }
    tail1->next=head2->next;
        tail2->next=NULL;//**必须要有,不然会在某些极端测试用例下会形成一个环,
                          //那便 是死循环了,栈溢出。**
        pHead=head1->next;
        free(head1);
        free(head2);
         return pHead;
    }
# };
全部评论

相关推荐

2025-12-26 00:57
门头沟学院 golang
菜菜_带带:作弊的前提是你得有真东西,不然很容易就备看出来了,至于混进去,都是面试造火箭,工作拧螺丝罢了
点赞 评论 收藏
分享
2025-12-19 21:53
门头沟学院 Java
想做OpenGL:不要一来就把自己定位这么低吧,把大厂当成目标,不断去学技术做项目,最后你至少能学到能找到中小厂的技术水平,你一上来就找这种两千块还要前后端都会的,其实对你用处不会很大,真去了也是打杂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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