My accepted solution (C++)


  • 0
    C
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void reorderList(ListNode *head) {
            
            // get the secondhalf list that is reversed
            ListNode* secondHalfList = getSecondHalfReverseList(head);
            ListNode* firstHalfList;
            
            // Merge two list (first two elements)
            ListNode* cursor = head;
            if(head!=NULL)
                firstHalfList = head->next;
            if(cursor != NULL && secondHalfList != NULL){
                cursor->next = secondHalfList;
                secondHalfList = secondHalfList->next;
                cursor = cursor->next;
            }
            
            // Merge two list
            while(firstHalfList != NULL && secondHalfList != NULL){
                cursor->next = firstHalfList;
                firstHalfList = firstHalfList->next;
                cursor = cursor->next;
                cursor->next = secondHalfList;
                secondHalfList = secondHalfList->next;
                cursor = cursor->next;
            }
            // Merge two list (last element)
            if(firstHalfList != NULL){
                cursor->next = firstHalfList;
                firstHalfList = firstHalfList->next;            
            }
            return;
            
        }
        // get the secondhalf list, and reverse the second list
        ListNode* getSecondHalfReverseList(ListNode *head){
            if(head == NULL){
                return NULL;
            }
            ListNode *first = head;
            ListNode *second = head;
            while(second != NULL && second->next != NULL){
                first = first->next;
                second = second->next->next;
            }
            
            second = first->next;
            first->next = NULL;
            ListNode* secondHalf = NULL;
            while(second != NULL){
                ListNode* tmp = secondHalf;
                secondHalf = second;
                second = second->next;
                secondHalf->next = tmp;
            }
            return secondHalf;
        }
    };

Log in to reply
 

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