My 4ms C++ solution, creating a new head node.


  • 2
    B
    class Solution {
        private:
        ListNode newHead;
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            newHead.next=head;
            ListNode * temp;
            temp=&newHead;
            while((--n)>=0)
            {
                temp=temp->next;
            }
            head=&newHead;
            while(temp->next!=NULL)
            {
                temp=temp->next;
                head=head->next;
            }
            temp=head->next;
            head->next=temp->next;
            delete temp;
            return newHead.next;
        }
        Solution():newHead(0){}
    };

Log in to reply
 

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