Both iterative and recursive C solution.


  • 0
    N
    struct ListNode* reverseList(struct ListNode* head) {
    	struct ListNode * Before = NULL;
    	struct ListNode * OriPresent = head;
    	while (OriPresent != NULL) {
    		struct ListNode * Present = (struct ListNode*)malloc(sizeof(struct ListNode));
    		Present->val = OriPresent->val;
    		Present->next = Before;
    		Before = Present;
    		OriPresent = OriPresent->next;
    	}
    	return Before;
    }
    

    ////////////////////////////////////////

    struct ListNode * reverse(struct ListNode * Before, struct ListNode * OriPresent) {
    	if (OriPresent == NULL) return Before;
    	struct ListNode * Present = (struct ListNode*)malloc(sizeof(struct ListNode));
    	Present->next = Before;
    	Present->val = OriPresent->val;
    	return reverse(Present, OriPresent->next);
    }
    
    struct ListNode* reverseList(struct ListNode* head) {
    	return reverse(NULL, head);
    }

Log in to reply
 

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