[LeetCode] Partition List
发布日期:2021-10-24 15:04:53 浏览次数:2 分类:技术文章

本文共 1689 字,大约阅读时间需要 5 分钟。

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Solution:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *partition(ListNode *head, int x) {        if(head == NULL) return head;                ListNode *ans_head = NULL,*ans_end = NULL, *tmp = head;        while(tmp != NULL)        {            if(tmp -> val < x)             {                   ListNode *ln = new ListNode(tmp -> val);                if(ans_head == NULL)                {                    ans_head = ln;                    ans_end = ln;                }                else                {                    ans_end -> next = ln;                    ans_end = ln;                }            }                        tmp = tmp -> next;        }                tmp = head;        while(tmp != NULL)        {            if(tmp -> val >= x)             {                   ListNode *ln = new ListNode(tmp -> val);                if(ans_head == NULL)                {                    ans_head = ln;                    ans_end = ln;                }                else                {                    ans_end -> next = ln;                    ans_end = ln;                }            }                        tmp = tmp -> next;        }                return ans_head;    }};

转载于:https://www.cnblogs.com/changchengxiao/p/3592988.html

转载地址:https://blog.csdn.net/weixin_30794491/article/details/99607597 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:木其工作室(专业程序代写服务)[原]ok6410学习笔记(12.kset学习记录)
下一篇:C#中有关的访问修饰符

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月23日 04时19分28秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章