4ms C++ easy to understand


  • 0
    B

    use three pointer

    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode *pre = head;
            ListNode *mid = head;
            ListNode *tail = head;
            
            if(pre->next==nullptr)
            {
                return NULL;
            }
            
            for(int i=0;i<n-1;i++)
            {
                pre = pre->next;
            }
            
            
            if(pre->next==nullptr)
            {
                head = head->next;
                return head;
            }
            
            while(pre->next!=nullptr)
            {
                pre = pre->next;
                tail = mid;
                mid = mid->next;
            }
            
            tail->next = mid->next;
            free(mid);
            return head;
        }
    };

Log in to reply
 

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