【C++】CM11 链表分隔

ઇଓ 欢迎来阅读子豪的博客(剑指offer刷题篇)

☾ ⋆有什么宝贵的意见或建议可以在留言区留言

ღღ欢迎 素质三连 点赞 关注 收藏

 码云仓库:补集王子 (YZH_skr) - Gitee.com

链表分割_牛客题霸_牛客网 (nowcoder.com)https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId=8&&tqId=11004&rp=2&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking

目录

 难点

思路

运用带哨兵位的头结点(尾插的题尽量都用哨兵位)

定义两个链表

尾插

连接+释放

考虑极端场景

需要把最后一个置空

整体代码


 难点

相对顺序不变

思路

运用带哨兵位的头结点(尾插的题尽量都用哨兵位)

定义两个链表

尾插

 

连接+释放

 

 

考虑极端场景

原来链表最后一个比x大

就会把大的那个写到新链表的最后一个去 但是这个的next是指向前面的 就会出现一个环

  

需要把最后一个置空

整体代码

class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) 
    {
        ListNode *greatertail , *greaterhead, *lesshead, *lesstail;
        greaterhead = greatertail = (struct ListNode*)malloc(sizeof(struct ListNode));    //哨兵位
        lesshead = lesstail = (struct ListNode*)malloc(sizeof(struct ListNode));    //哨兵位
        greaterhead -> next = NULL;
        lesshead ->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;
    }
};

记得 三连哦~

  • 30
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 32
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

补集王子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值