Slow but easy c++ solution for beginner


  • 0
    V

    very very very very slow(only beat 9%) but it's easy to understand.

    class Solution {
        public:
            ListNode* oddEvenList(ListNode* head) {
                if(head==NULL)return NULL;
                int flag = 0;
                ListNode* pointer = head;
                ListNode* oddLinkstart = new ListNode(0);
                ListNode* evenLinkstart = new ListNode(0);
                ListNode* oddLinkend = oddLinkstart;
                ListNode* evenLinkend = evenLinkstart;
                while(pointer!=NULL){
                    if(flag==0){
                        oddLinkend->next = pointer;
                        evenLinkend->next = NULL;
                        oddLinkend = oddLinkend->next;
                        pointer = pointer->next;
                        flag = 1 - flag;
                    }
                    else{
                        evenLinkend->next = pointer;
                        oddLinkend->next = NULL;
                        evenLinkend = evenLinkend->next;
                        pointer = pointer->next;
                        flag = 1 - flag;
                    }
                }
                oddLinkend->next = evenLinkstart->next;
                return oddLinkstart->next;
            }
        };

Log in to reply
 

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