My C++ Solution

  • 5
    class Solution {
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode* front = new ListNode(0);
    		front->next = head;
    		ListNode* prev = front;
    		ListNode* post = front;
    		while (prev != nullptr){
    			prev = prev->next;
    			if (n<0)	post = post->next;
    		ListNode* temp = post->next;
    		post->next = temp->next;
    		delete temp;
    		return front->next;

  • 0

    why you create another list 'front'?why not delete the element and return 'head'?

  • 0

    when you delete an element in a singly linked list, you have to know its previous node.
    but the head node has not a previous node.
    when you add a new front node ,you can handle the head node as same as the other nodes.

  • 0

    thank you very much!

Log in to reply

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