6ms solution


  • 0

    /**

    • 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* cur=head;
      ListNode* cur0=head;
      ListNode* cur00=head;
      while(cur!=NULL&&cur->val<x){
      cur0=cur;
      cur=cur->next;
      }

       cur00=cur;
       if(cur==NULL||cur->next==NULL)return head;
       
       while(cur!=NULL){
            ListNode* tmp0=cur0->next;
            ListNode* tmp1=cur->next;
            ListNode* tmpcur=cur;
           
           if(cur->val<x){//insert
              // cout<<cur0->val<<":"<<cur->val<<":"<<cur00->val<<endl;
               
               if(head==cur0&&head->val>=x){
                   cur00->next=cur->next;
                   cur->next=head;
                   head=cur;
                   cur0=head;
                   cur=cur00->next;
                   continue;
               }
               if(cur0->next==cur){
                   int a=cur0->val;
                   cur0->val=(cur->val);
                   cur->val=a;
                   cur0=cur;
                   cur=cur0->next;
                   cur00=cur;
                   continue;
               }
               cur0->next=cur;
               cur0=cur;
               cur->next=tmp0;
               cur00->next=tmp1;
               cur=cur00->next;
               
               continue;
           }
           cur00=cur;
           cur=cur->next;
       }
       return head;
      

      }
      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.