Leetcode17 - 328. Parity linked list

insert image description here
Set a flag to judge the parity + parity linked list pointer, and the last two linked lists can be merged

class Solution {
    
    
public:
    ListNode* oddEvenList(ListNode* head){
    
    
          if(head==NULL||head->next==NULL||head->next->next==NULL)return head;

           ListNode *odd=head,*even=head->next;
           ListNode *oddhead=head,*evenhead=head->next;
           ListNode *cur=head->next->next;
           //为true表示为奇数个,false为偶数个
           bool flag=true;

           while(cur!=NULL){
    
    
                if(flag){
    
    
                    odd->next=cur;
                    odd=cur;
                    //printf("odd=%d\n",odd->val);
                }else{
    
    
                   even->next=cur;
                   even=cur;
                   
                }
                cur=cur->next;
                flag=!flag;
           }

           odd->next=evenhead;
           even->next=NULL;
           
       
           return oddhead;

    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324107895&siteId=291194637