0ms C iteration version


  • 0
    D
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        struct ListNode* cur = head;
        struct ListNode* target = NULL;
        struct ListNode* pre = NULL;
        int i = 1;
        while(cur)
        {
            cur = cur->next;
            if(i < n)
            {
                ++i;
            }else
            {
                pre = target == NULL ? NULL : target;
                target = target == NULL ? head : target->next;
            }
        }
        if(target)
        {
            if(pre)
            {
                pre->next = target->next;
            }else
            {
                head = target->next;
            }
            target->next = NULL;
        }
        return head;
    }

Log in to reply
 

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