LeetCode 面试题02.04.分割链表

LeetCode 面试题02.04.分割链表 C写法

image-20240713175326367

思路🤔:

​ 将x分为两段,一段放小于x的值,另一段放大于x的值。开辟四个指针lesshead、lesstail、greaterhead、greatertail,head为哨兵位,防止链表为空时情况过于复杂,tail为尾结点,将链表的值进行大小判断后尾插完成分段,分段后再链接,最后释放哨兵位完成整个链表的分割。

代码:

struct ListNode* partition(struct ListNode* head, int x){
       struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;
       lesshead = lesstail = (struct ListNode*)malloc(sizeof(struct ListNode));
       greaterhead = greatertail = (struct ListNode*)malloc(sizeof(struct ListNode));
       lesstail->next = greatertail->next = NULL; //将链表分为两段存储
       struct ListNode* cur = head;
       while(cur)
       {
            if(cur->val < x) //小于x尾插在less段
            {
                lesstail->next = cur;
                lesstail = lesstail->next;
            }
            else
            {
                greatertail->next = cur;
                greatertail = greatertail->next;
            }
            cur = cur->next;
       }
       lesstail->next = greaterhead->next; //链接两段链表,哨兵位不放数据所以要链接到next
       greatertail->next = NULL; //单链表最后要指向空
       struct ListNode* list = lesshead->next; //完整链表
       free(greaterhead);
       free(lesshead);
       return list;
}

image-20240713185458069

相关推荐

  1. leetcode面试 02.07. 相交

    2024-07-14 09:58:02       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 09:58:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 09:58:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 09:58:02       58 阅读
  4. Python语言-面向对象

    2024-07-14 09:58:02       69 阅读

热门阅读

  1. 八部金刚功-1.0.5-july 14th

    2024-07-14 09:58:02       24 阅读
  2. R 绘图 - 中文支持

    2024-07-14 09:58:02       22 阅读
  3. 不遵守全局主键配置【PGSQL】

    2024-07-14 09:58:02       19 阅读
  4. 手撕排序算法:冒泡排序

    2024-07-14 09:58:02       25 阅读
  5. 深入探究:Spring 中的消息队列实现方式

    2024-07-14 09:58:02       22 阅读
  6. 中介子方程五十八

    2024-07-14 09:58:02       15 阅读
  7. 【Perl】Perl 语言入门

    2024-07-14 09:58:02       19 阅读
  8. 2024-07-13 Qt6.5版本后视频渲染

    2024-07-14 09:58:02       25 阅读
  9. 格式化输出游戏装备的名称和单价

    2024-07-14 09:58:02       17 阅读
  10. OTP防重放攻击

    2024-07-14 09:58:02       20 阅读
  11. 排序之冒泡排序

    2024-07-14 09:58:02       22 阅读
  12. flutter弹窗高度过高,在弹出键盘后布局溢出问题

    2024-07-14 09:58:02       22 阅读
  13. Pytorch lr_scheduler 调整学习率

    2024-07-14 09:58:02       22 阅读
  14. C#中反射与MVC和AOP

    2024-07-14 09:58:02       27 阅读