Simple C++ iterative and recursive


  • 0

    Iterative

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode* pre(NULL), *cur(head), *next;
            while(cur){
                next = cur->next;
                cur->next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    };
    

    Recursive

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if (!head || !head->next) return head;
            ListNode* node = reverseList(head->next);
            head->next->next = head;
            head->next = NULL;
            return node;
        }
    };
    

Log in to reply
 

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