c++ easy solution using Stack


  • 0
    M
        ListNode* reverseList(ListNode* head) {
            ListNode preHead(0), *p;
            p = &preHead;
            p->next = head;
            stack<ListNode*>myStack;
    // push all elements to stack
            while(head != NULL){
                myStack.push(head);
                head = head->next;
            }
    //get the head (last element as first)
            if( !myStack.empty()){
                head = myStack.top();
                myStack.pop();
                p->next = head;
            }
    //pop all other elements to first->next
            while(!myStack.empty()){
                head->next = myStack.top();
                myStack.pop();
                head = head->next;
            }
            if(head != NULL)
            head->next = NULL;
            return p->next;
        }

Log in to reply
 

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