using recursive method to reverse the LinkedList


  • 0
    L

    using recursive method to reverse the LinkedList

        ListNode* reverseList(ListNode* head) {
            ListNode* phead=nullptr;//new head of the reverse LinkedList
            reverse(head,phead);
            return phead;
        }
        ListNode* reverse(ListNode* head,ListNode * &phead){
            if(head == nullptr )
                return nullptr;
            /**hit the end ,phead is the start of the reverse LinkedList**/
            if(head->next == nullptr){
                phead = head;
                return head;
            }
            ListNode* p = reverse(head->next,phead);//reverse the right part of head node
            if(p != nullptr){
                /**very import if head is the source head of the original LinkedList*/
                head->next = nullptr;
                p->next = head;
                return head;//return the tail of the reversed LinkedList
            }
            return nullptr;
        }
    

Log in to reply
 

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