Sharing my 4ms C++ solution


  • 0
    T
    /**
     * 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) {
            ListNode* spark = new ListNode(0);
            spark->next = head;
            ListNode* ahead = head;
            int i;
            for(i=0; i<n; i++)
                ahead = ahead->next;
            ListNode* behind = spark;
            
            while(ahead)
            {
                ahead = ahead->next;
                behind = behind->next;
            }
            
            ListNode* tmp = behind->next;
            behind->next = behind->next->next;
            delete tmp;
            ListNode* result = spark->next;
            delete spark;
            return result;
        }
    };

  • 0
    B

    Could you tell me why we should add a ListNode* spark before head? And why return spark->next, not head? I have tried not to add a spark and just return head, but didn't work.


Log in to reply
 

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