6ms c++ solution


  • 0
    I

    Keep track of the nodes immediate forward and back of the current node.

    Redirect next pointer to the back and make next node the current node.

    Repeat until end of linked list!

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if (!head) return NULL;
            ListNode* back = NULL;
            while (head->next) {
                ListNode* temp = head->next;
                head->next = back;
                back = head;
                head = temp;
            }
            head->next = back;
            return head;
        }
    };
    

Log in to reply
 

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