题解 | #链表分割#

链表分割

https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstdlib>
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        //这里带哨兵位
        struct ListNode*greaterhead,*greatertail,*lesshead,*lesstail;
        lesshead=lesstail=(struct ListNode*)malloc(sizeof(struct ListNode));
       greaterhead=greatertail=(struct ListNode*)malloc(sizeof(struct ListNode));
        greatertail->next=NULL;
        lesstail->next=NULL;
         struct ListNode*cur=pHead;
         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;

         struct ListNode*head=lesshead->next;
         free(greaterhead);
         free(lesshead);
         return head;
    }
};

全部评论

相关推荐

MinJerous:虽然我一直说 计算机不怎么卡学历 但是至少得一本
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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