My C++ Solution


  • 5
    class Solution {
    public:
        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;
    			n--;
    		}
    		ListNode* temp = post->next;
    		post->next = temp->next;
    		delete temp;
    		return front->next;
        }
    };

  • 0
    S

    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
    S

    thank you very much!


Log in to reply
 

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