Two solutions, iterative 11ms, recursive 10ms, C++


  • 0
    F

    Both iterative and recursive solutions are listed below, costs 11ms and 10ms respectively.

    //Solution 1: iterative solution, 11ms
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode* pre  = NULL;
            ListNode* cur  = head;
            ListNode* next = NULL;
            while (cur != NULL) {
                ListNode* next = cur->next;
                cur->next      = pre;
                pre            = cur;
                cur            = next;
            }
         
            return pre;
        }   
    };
    
    //Solution 2: recursive solution, 10ms
    class Solution {
    public:
        ListNode* ans = NULL;
        ListNode* reverseList(ListNode* head) {
            reverse(NULL, head);
            return ans;
        }
        
        ListNode* reverse(ListNode* pre, ListNode* cur) {
            if (cur == NULL) {
                ans = pre;
                return pre;
            }
            reverse(cur, cur->next)->next = pre;
        }
    };
    

    Welcome visit all the solutions on: https://github.com/fanfank/leetcode


Log in to reply
 

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