Easiest 4ms C++ solution.Very easy to understand.


  • 2
    S
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            
            ListNode *p1,*p2,*cur;
            p1=p2=head;
            for(int i=0;i<n;i++){
                p2=p2->next;
            }
            //to handle the special case.
            if(p2==NULL){
                head=head->next;
                delete p1;
                return head;
            }
            
            while(p2->next!=NULL){
                p2=p2->next;
                p1=p1->next;
            }
            cur=p1->next;
            p1->next=cur->next;
            delete cur;
            return head;
            
            
        }
    };
    

  • 0
    Q

    is this the Pseudo code? I am a beginner of c++.and I tried this idea.but got "runtime error".


  • 0
    S

    No this is not a pseudo code, this code is submitted and also accepted.
    Here is the idea which you can try to code, if the code was not very clear.

    You first need to have the nth node form the end.
    To do that.
    --you keep two pointers n nodes apart.(fast pointer and slow pointer)
    --traverse each pointer one by one until one of them reaches NULL. (of course the fast pointer reaches NULL).
    --Now, the current position of the slow pointer is the n-1th node.
    --Now link n-1th node to the next of nth node.
    DONE.

    Of course after all this you handle some special cases which i have done above.
    Debug your code if you still dont get it.


  • 0
    Q

    thanks so much.I'll try your idea


Log in to reply
 

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