My simple one pass solution with only one loop


  • 1
    S
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if (head == NULL || n == 0) return head;
    
            struct ListNode *p0 = head, *p1= head;
            int cnt = 0;
            while (p0->next != NULL) {
                ++cnt;
                p0 = p0->next;
                if (cnt > n)
                    p1 = p1->next;
            }
    
            if (cnt == n - 1) return head->next;
    
            p1->next = p1->next->next;
            return head;
        }
    };
    

Log in to reply
 

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