Share my 4ms solution


  • 6
    Y
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {//开辟一个头结点就可以解决问题啦!
            if(!head -> next) return NULL;
            ListNode* headt = new ListNode(0);
            headt -> next = head;
            ListNode* forward = headt;
            ListNode* tail = headt;
            for(int i = 0; i < n; i++){
                if(forward -> next) forward = forward -> next;
            }
            while(forward -> next){
                forward = forward -> next;
                tail = tail -> next;
            }
            tail -> next = tail -> next -> next;
            return headt -> next;
        }
    };

  • 0
    C

    memory leak. The deleted one is not released. Also, when n < list length, may wrong.


  • 0
    Y

    Thank you!!~


Log in to reply
 

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