My clean C++ solution, works well with invalid n


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

Log in to reply
 

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