My accepted O(n) solution in C++,Any advising?


  • 0
    K
    /**
     * 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* pre=head;
    		for(int i=0;i<n;i++)
    			pre=pre->next;
    		if(NULL==pre)
    		{
    			return head->next;
    		}
    		else
    		{
    			ListNode* post=head;
    			ListNode* parent;
    			while(pre!=NULL)
    			{   
    				parent=post;
    				pre=pre->next;
    				post=post->next;
    			}
    			parent->next=post->next;
    			return head;
    		}		
        }
    };

  • 0
    R

    You aren't freeing memory what leads to memory leaks. You need to delete pointers, not only skip them in the list.


  • 0
    X

    If head==NULL and n=0 (i.e. {},0), the code won't work because head and pre don't have a next.


Log in to reply
 

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