One loop C++ solution


  • 2
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if (!head) return head;
            ListNode dummy(0), * t = &dummy, *s = &dummy;
            dummy.next = head;
            while (t && t->next) {
                if (n-- <= 0) s = s->next;
                t = t->next;
            }
            s->next = s->next->next;
            return dummy.next;
        }
    };
    

Log in to reply
 

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