Sharing my 8ms in-place solution


  • 3
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            // in-place linked list reversal
            ListNode* result = NULL;
            ListNode* p = head;
            ListNode* temp = NULL;
            
            while(p)
            {
                temp = p->next;
                p->next = result;
                result = p;
                p = temp;
            }
            
            return result;
        }
    };

Log in to reply
 

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