Two pointers and a dummy head.My AC code/C++


  • 0
    J
    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode dummy(0);
            ListNode *p1=&dummy,*p2=p1;
            dummy.next=head;
            for(int i=0;i<n;++i){
                p1=p1->next;
            }
            while(p1->next!=NULL){
                p1=p1->next;
                p2=p2->next;
            }
            p2->next=p2->next->next;
            return dummy.next;
        }
    };

  • 0
    C

    This is exactly what I did !

        ListNode *removeNthFromEnd(ListNode *head, int n) {
        if (!head || !n)
            return head;
        ListNode *head_ = new ListNode(-1); // dummy
        head_->next = head;
        ListNode *i1, *i2; // traverse n-elements apart
        for (i1= head_; i1 && n  ; --n) { i1 = i1->next ; }
        for (i2= head_; i1->next ;    ) { i1=i1->next, i2= i2->next; }
        i2->next = i2->next->next; // skip
        return head_->next;
    }
    

Log in to reply
 

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