C99, concise solution with dummy head.

  • 0

    With the usage of dummy head, there is no need to check the boundary condition that the head is the node which should be deleted .

     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        struct ListNode dummy, *l = &dummy, *r = head;
        dummy.next = head;
        while (n--) r = r->next;
        while (r) {
            l = l->next;
            r = r->next;
        l->next = l->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.