11/6-line Iterative/Recursive C++ Solution


  • 1
    L

    I think this is the most concise solution, no?

    // Iterative
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *cur=head, *nex=head->next;
        cur->next=NULL;
        while(nex->next) {
            ListNode* tmp=nex->next;
            nex->next=cur;
            cur=nex;
            nex=tmp;
        }
        nex->next=cur;
        return nex;
    }
    
    // Recursive
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL) return head; // head->next==NULL is the base case for recursion
        ListNode* nex = head->next;
        head->next=NULL;
        ListNode* newHead = reverseList(nex);
        nex->next=head;
        return newHead;
    }

Log in to reply
 

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