题解 | #链表分割#

链表分割

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// write code here
        //创建非空的大,小链表
        ListNode*lesshead,*lesstail;
        lesshead=lesstail=(ListNode*)malloc(sizeof(ListNode));
        ListNode*greaterhead,*greatertail;
        greaterhead=greatertail=(ListNode*)malloc(sizeof(ListNode));
        ListNode*pcur=pHead;
        //遍历当前链表
        while(pcur)
        {
             if((pcur->val)<x)
             {
                lesstail->next=pcur;
                lesstail=lesstail->next;
             }
             else
             {
                greatertail->next=pcur;
                greatertail=greatertail->next;
             }
             pcur=pcur->next;
        }
        //避免成为环形链表
        greatertail->next=NULL;
        //大小链表相连接
        lesstail->next=greaterhead->next;
        ListNode*ret=lesshead->next;
        free(lesshead);
        free(greaterhead);
        lesshead=greaterhead=NULL;
        return ret;

       }

};

全部评论

相关推荐

勇敢的90后想交流:我愿意付费上班,楼主你就安心字节待着吧,我是真的喜欢上班
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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