What's wrong with my c code?


  • 0
    L
    struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *current = NULL, *beforeCurrent = NULL, *afterCurrent = NULL;
    if ( head != NULL && head->next != NULL) {
    	beforeCurrent = head;
    	current = beforeCurrent->next;
    	while ( current != NULL) {
    		afterCurrent = current->next;
    		current->next = beforeCurrent;
    		beforeCurrent = current;
    		current = afterCurrent;
    	}
    }
    return beforeCurrent;
    

    }

    For example, it will be wrong when the input is [1, 2].


  • 0
    L

    The error is time out.

    The right code is like this:

    while ( current != NULL) {
    	afterCurrent = current->next;
    	// reverse
    	if (beforeCurrent->next == current) {
    		beforeCurrent->next = NULL;
    	}
    	current->next = beforeCurrent;
    	beforeCurrent = current;
    	current = afterCurrent;
    }
    

    At the first time, head->next should be set NULL. Otherwise, it will be a cycle.


Log in to reply
 

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