Why time limit exceeded?(cpp)


  • 0
    J

    It seems that there's something wrong with "p->next = pre". Why?
    Here's my code!

    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head ->next == NULL)
            return head;
        ListNode *pre = head;
        ListNode *p = head -> next;
        ListNode *after = p -> next;
        while(p -> next != NULL)
        {
            p->next = pre;
            pre = p;
            p = after;
            after = after -> next;
        }
        p -> next = pre;
        return p;
    }

  • 0
    B

    I had the same issue, if I'm not mistaken.

    When you reverse the linked list the last node should have a next of NULL. The last node in the reversed linked list is the first node! So I believe you want to initialize pre, by writing pre->next = NULL;

    Without it if you try to traverse the linked list you will never finish, since the last nodes next is not NULL. In fact if the last node's next is the original value then there will be a cycle.


Log in to reply
 

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