3 Pointers with C++ in 9ms


  • 0
    H

    3 pointers(2 move and 1 temp) to solve this problem with C++

    /**
     * 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) {
            if(head==NULL||head->next==NULL)
                return head;
            ListNode* p = head,*q = p->next,*temp=0;
            p->next = NULL;
            while(q){
                temp = q->next;
                q->next = p;
                p = q;
                q = temp;
            }
            return p;
        }
    };
    

Log in to reply
 

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