Accepted 6ms C++ Iterative solution


  • 0
    S
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(!head || !head->next) return head; /*head is NULL or there is only one Node,just return head*/
            ListNode *pre=NULL,*next=head->next;/*define the previous node and the next node*/
            while(next){
                head->next=pre;/*reverse*/
                pre=head;/*update pre*/
                head=next;/*update head*/
                next=head->next;/*update next*/
            }
            head->next=pre;/*finally reverse*/
            return head;
        }
    };
    

Log in to reply
 

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