simple and easy to understand C++ solution.


  • 0
    L

    simple and easy to understand C++ solution.

    ListNode* removeNthFromEnd(ListNode* head, int n) {
    	ListNode *front = head, *rear = head; // front go first, then together
    	while (n--) front = front->next;      // front go n steps
    	if (!front) return head->next;        // if n is equal to the length of list, delete first node
    	while (front->next)                   // go together til front get to end
    	{
    		rear = rear->next;
    		front = front->next;
    	}
    	rear->next = rear->next ? rear->next->next : NULL; // delete that node
    	return head;
    }
    

Log in to reply
 

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