leetcode 86. Partition List【分裂ListNode】

https://leetcode.com/problems/partition-list/description/

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

将比x大的放在左边,大于等于x的放在右边

开始想到了是分成两个ListNode

写啊写啊

各种逻辑错误

最后更无语的是 flag变量设置bool类型 还赋值-1 发现怎么也没变啊

 

/**
 * 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 || head->next==NULL)
            return head;
        ListNode *Rt=new ListNode(-1);
        ListNode *R=Rt;
        ListNode *q=new ListNode(-1);
        q->next=head;
        int flag=1;
        if(head->val < x)
            flag=0;
        while(q->next!=NULL){
            if(q->next->val >= x){
                R->next=q->next;
                q->next=q->next->next;
                R=R->next;
                R->next=NULL;
            }
            else{
                q=q->next;
                if(1==flag){
                    flag=-1;
                    head=q;
                }
            }
            //cout<<flag<<endl;
        }
        
        if(flag==1)
            return Rt->next;
        q->next=Rt->next;
        return head;
    }
};

 

全部评论

相关推荐

白火同学:只是实习的话,你这份简历应该也差不多了。真要优化的话,因为面实习的话,没有开发经验,面试更重视技术栈水平。 1、重视JavaSE的基础吧,集合、泛型算是比较基础的基础,多线程、反射、JVM内存模型才是基础; 2、技术栈写到具体的点,比如Elasticsearch的使用写到某个点,限制面试官自由发挥,防止问了相关问题最后又答不上,如果真没把握建议不写,降低面试官的心理预期; 3、技术栈不要重复,比如技术栈第二条和第八条可以合并改为“熟悉Redis中间件,包括基本数据结构、缓存策略、持久化机制,了解缓存三剑客及其解决方案,并有相关项目经验。”; 4、项目指标量化,比如“达到xx秒的响应速度”(不过这个就有点偏校招社招的要求了,实习简历不写也无伤大雅)。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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