C++ O(n) complexity, O(1) space solution


  • 1
    L
    /**
     * 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) || (!head->next)) return head;
            ListNode* current;
            current = head->next;
            if (!head->next->next) {
                head->next = NULL;
                current->next = head;
                return current;
            }
            ListNode* prev;
            ListNode* temp;
            ListNode* temp2;
            
            head->next = NULL;
            prev = current->next;
            current->next = head;
            while(prev->next){
                temp = prev->next;
                prev->next = current;
                temp2 = prev;
                prev = temp;
                current = temp2;
            }
            prev->next = current;
            return prev;
        }
    };

  • 0
    B
    This post is deleted!

Log in to reply
 

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