Partition List

来源:互联网 发布:明道软件使用 编辑:程序博客网 时间:2024/06/04 18:39
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head==NULL||head->next==NULL) return head;
        queue<ListNode*>Q1;
        ListNode* p=head,*pre=head,*plast,*pre1;
        while(p)
        {
           
            if(p->val>=x)
            {
                
                Q1.push(p);   //找出大于X的值存入队列;
            }
            
           p=p->next;   
            
        }
        
        while(pre&&pre->val>=x)
        {
            pre=pre->next;        //找出头结点;
        }
        
        
         
        if(pre==NULL) 
        {
            return head;        //全部大于X则返回head;
            
        }
        
        //plast=p;
        pre1=pre;
        p=pre;
        while(p)
        {
            if(p->val>=x)
            {
                if(p->next)   
                {pre1->next=p->next;
                p=p->next;}
                else pre1->next=NULL,p=p->next;   //注意一定要写p=p->next; 
            
            }
           else
            {
                pre1=p;
                p=p->next;
                
            }
            
        }                                                      //为了找出小于X的尾;
        plast=pre1;                                 //小于X的尾;
      //  if(plast==NULL)  plast=pre1; 
        while(!Q1.empty())
        {
            plast->next=Q1.front();
            Q1.pop();
            plast=plast->next;
        }
        plast->next=NULL;
        
        return pre;
   }

};

队列一定要判空,循环一定要能否跳出。 null不能再接null,等于号几个一定要看清楚

双队列法

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head==NULL||head->next==NULL) return head;
        queue<ListNode*>Q1,Q2;
        ListNode* p=head,*pre=head,*plast,*pre1;
        while(p)
        {
           
            if(p->val>=x)
            {
                
                Q1.push(p);   //找出大于X的值存入队列;
            }
            else Q2.push(p);
           p=p->next;   
            
        }
        if(Q2.empty())
        {
           plast=Q1.front();
          Q1.pop();
          head=plast; 
           while(!Q1.empty())
      {
         plast->next=Q1.front();
         Q1.pop();
        plast= plast->next;
      }
      plast->next=NULL;
      return head;
        }
        
        
        head=Q2.front();
        p=head;
        Q2.pop();
       
      while(!Q2.empty())
      {
          p->next=Q2.front();
          p=p->next;
          Q2.pop();
      }
      plast=p;
      if(plast!=NULL) plast->next=NULL;
      if(plast==NULL) 
      {
          plast=Q1.front();
          Q1.pop();
          head=plast;
      }
      
      while(!Q1.empty())
      {
         plast->next=Q1.front();
         Q1.pop();
        plast= plast->next;
      }
      plast->next=NULL;
      return head;
      
    }
};

0 0
原创粉丝点击