My C++ O(2n) time and O(2n) space, needs improving:)


  • 0
    K
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            if(head == NULL) return head;
            if(head->next == NULL) return head;
            ListNode* temp = head;
            ListNode* begin = new ListNode(head->val);
            ListNode* temp1 = begin;
            int count = 0;
            while(temp != NULL)
            {
                temp = temp->next;
                count++;
            }
            temp = head;
            while(count > 1)
            {
                printf("%d", temp->val);
                printf("%d", count);
                if(temp->next != NULL && temp->next->next != NULL) 
                    temp = temp->next->next;
                else
                    temp = head->next;
                    
                temp1->next = new ListNode(temp->val);
                temp1 = temp1->next;
                count--;
            }
            temp1->next = NULL;
            return begin;
        }
    };

Log in to reply
 

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