题解 | #链表分割#

链表分割

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) {
        ListNode* bigGuard,*smallGuard,*bigTail,*smallTail;
        bigGuard=bigTail=(ListNode*)malloc(sizeof(struct ListNode));
        smallGuard=smallTail=(ListNode*)malloc(sizeof(struct ListNode));
        bigTail->next=smallTail->next=NULL;
        ListNode* cur=pHead;
        while(cur)
        {
            if(cur->val<x)
            {
                smallTail->next=cur;
                smallTail=smallTail->next;
            }
            else
            {
                bigTail->next=cur;
                bigTail=bigTail->next;
            }
            cur=cur->next;
        }
        bigTail->next=NULL;//需要把大数尾的next置空,否则可能出现死循环
        smallTail->next=bigGuard->next;
        pHead=smallGuard->next;
        free(smallGuard);
        free(bigGuard);
        return pHead;
    }
};

全部评论

相关推荐

07-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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