[recommend for beginners]clean C++ implementation with detailed explaination


  • 1

    As I first get the question. I do not AC for one submittion. So the problem is that I should make clear about all the border cases.
    To find the tail of the odd-linked-list , just traverse the linked list to find the tail .

      class Solution {
        public:
            ListNode* oddEvenList(ListNode* head) {
                if(!head || !head->next)    return head;
                
                ListNode *odd_head = head;
                ListNode *even_head = head->next;
                ListNode *odd_cur=odd_head, *even_cur=even_head;
                
                 /***   seperate the odd-linked-list and even-linked-list    ***/
                while(odd_cur && even_cur){
                    /**  linked-the-odd-ordered-pointers  **/
                    odd_cur->next=even_cur->next;
                    odd_cur=odd_cur->next;
                    /**  linked-the-even-ordered-pointers  **/
                    if(even_cur && even_cur->next){
                        even_cur->next=even_cur->next->next;
                        even_cur=even_cur->next;
                    }
                }
                
                /***    move to the tail of the odd linked list    ***/
                ListNode *odd_tail=odd_head;
                while(odd_tail->next){
                    odd_tail=odd_tail->next;
                }
                
                /***  link the odd linked list tail to the head of the even linked list  ***/
                odd_tail->next=even_head;
                
                return odd_head;
            }
        };

Log in to reply
 

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