LeetCode 206. Reverse Linked List

Reverse a singly linked list.


This one is supposed to be easy. However, a lot of companies tend to ask for several versions to solve it. Facebook tends to ask for iteration and recursive.


// Method1:

ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* dummy = NULL;
        while(head) {
            ListNode* tmp = head->next;
            head->next = dummy;
            dummy = head;
            head = tmp;
        }
        return dummy;
    }

// Method2: Recursion.

ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* second = head->next;
        head->next = NULL;
        
        ListNode* rest = reverseList(second);
        second->next = head;
        return rest;
    }


你可能感兴趣的:(LeetCode 206. Reverse Linked List)