Simple clean yet best solution in C++


  • -1
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) 
        {
            if(!head || !head->next) return head;
            ListNode newHead(0), *p = head->next, *t = NULL, *next = NULL;
            t = &newHead;
            t->next = head;
            t->next->next = NULL;
            while(p)
            {
                next = p->next;
                p->next = t->next;
                t->next = p;
                p = next;
            }
            return newHead.next;
        }
    };

  • 0

    Further simplified solution

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) 
        {
            ListNode newHead(0);
            ListNode *p = head, *next = NULL;
            while(p)
            {
                next = p->next;
                p->next = newHead.next;
                newHead.next = p;
                p = next;
            }
            return newHead.next;
        }
    };
    
    

Log in to reply
 

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