Can anyone help me check my C++ code. It only works with even number


  • 0
    W

    My code works when there are even number of nodes,like [1,2,3,4] or [1,2,3,4,5,6,7,8]. But when there are odd number, like[1,2,3], I get TLE. In my IDE my code works all well.
    ListNode* oddEvenList(ListNode* head) {
    if(head==NULL||head->next==NULL) return head;
    ListNode* evenhead=head->next;
    ListNode *odd=head,*even=evenhead,*all=evenhead->next;
    int sign=1;
    while(all!=NULL)
    {
    if(sign==1)
    odd->next=all,odd=odd->next;
    else
    even->next=all,even=even->next;
    all=all->next;
    sign=-sign;
    }
    odd->next=evenhead;
    return head;
    }


  • 0
    W
    ListNode* oddEvenList(ListNode* head) {
            if(head==NULL||head->next==NULL) return head;
            ListNode* evenhead=head->next;
            ListNode *odd=head,*even=evenhead,*all=evenhead->next;
            int sign=1;
            while(all!=NULL)
            {
                if(sign==1)
                    odd->next=all,odd=odd->next;
                else
                    even->next=all,even=even->next;
                all=all->next;
                sign=-sign;
            }
            odd->next=evenhead;
            return head;
        }
    

Log in to reply
 

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