C++ iteration and recursion beautiful solution


  • 1
    C

    Iteration:

    ListNode* reverseList(ListNode* head) {
            ListNode* cur = head;
            ListNode* pre = NULL;
            while(cur){
                ListNode* next = cur->next;
                cur->next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    

    Recursion:

    ListNode* reverseList(ListNode* head) {
            return help(head, NULL);
        }
        ListNode* help(ListNode* cur, ListNode* pre){
            if(!cur) return cur;
            ListNode* next = cur->next;
            cur->next = pre;
            return !next ? cur : help(next, cur);
        }
    

  • 1
    R

    What a beautiful solution! Even though I cannot read C++, I can feel it~


Log in to reply
 

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