首页 > 其他 > 详细

leetcode 86 Partition List

时间:2020-04-02 11:07:57      阅读:64      评论:0      收藏:0      [点我收藏+]

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||!head->next) return head;
        ListNode ln(-1);ln.next=head;
        ListNode* pre=&ln,*cur=head,*node=pre;
        while(cur) {
            if(cur->val>=x) {
                while(cur&&cur->val>=x) {
                    node=cur;
                    cur=cur->next;
                }
                if(!cur) break;
                node->next=cur->next;
                cur->next=pre->next;
                pre->next=cur;
                pre=cur;
                cur=node->next;
            }
            else {
                if(pre->next!=cur) {
                    node->next=cur->next;
                    cur->next=pre->next;
                    pre->next=cur;
                    pre=cur;
                    cur=node->next;
                }
                else {
                    pre=cur;
                    cur=cur->next;
                }
            }
            
        }
        return ln.next;
    }
};

2. 

/**
 * 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) {
        ListNode less(0),more(0);
        ListNode* cur=head,*lessp=&less,*morep=&more;
        while(cur) {
            if(cur->val<x) {
                lessp->next=cur;
                lessp=lessp->next;
            }
            else {
                morep->next=cur;
                morep=morep->next;
            }
            cur=cur->next;
        }
        morep->next=nullptr;
        lessp->next=more.next;
        return less.next;
    }
};

 

leetcode 86 Partition List

原文:https://www.cnblogs.com/LiuQiujie/p/12617689.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!