Partition List | LeetCode 8ms C++Solution

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.

解题思路:这道题其实就是链表的操作,难度在于指针的移动以及边界的检查。说一下我解题的思路大概是这样:

需求:遍历每一个元素,找出小于value的节点,然后将该节点移动到前面某个地方,接下来继续往后遍历。

问题就出来了,当找出小于value节点之后,移动的目的位置如果确定。依据题意,第一次移动的位置就是第一个大于等于value节点的前一个位置,使用一个指针记住这个位置,后面找到的节点依次往后,这样就可以保证相对位置不变。需要注意的一个列外就是,第一个插入的位置是链表头,这时候需要单独处理。代码如下:

ListNode* partition(ListNode* head, int x) {
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* pre=head;
        ListNode* first_gre=head;
        while(first_gre != NULL && first_gre->val < x){
            pre = first_gre;
            first_gre = first_gre->next;
        }
        if(first_gre == NULL || first_gre->next == NULL)
            return head;
        bool flag=false;
        //标识第一次插入为头部
        if(first_gre==head)
            flag=true;
        ListNode* second_pre=first_gre;
        while(first_gre->next!=NULL){
            first_gre=first_gre->next;
            if(first_gre->val < x){
                second_pre->next=first_gre->next;
                if(flag){
                    first_gre->next=head;
                    head=first_gre;
                    flag=false;
                    pre=head;
                }else{
                    first_gre->next=pre->next;
                    pre->next=first_gre;
                    pre=pre->next;
                }
                first_gre=second_pre;
                if(first_gre==NULL)
                    break;
                //      return head;
            }else{
                second_pre=first_gre;
            }
        }
        
        return head;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值