Remove Nth Node From End of List [LeetCode]

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.



   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

Summary: Be careful about corner cases, like n = 1,  or size of linked list equals to n.

 1     ListNode *removeNthFromEnd(ListNode *head, int n) {

 2         vector<ListNode *> cache;  // size should be n + 1 or n (in this case, size of linked list is n)

 3         ListNode * current = head;

 4         while(current != NULL){

 5             cache.push_back(current);

 6             if(cache.size() > n + 1)

 7                 cache.erase(cache.begin());

 8             current = current -> next;

 9         }

10         

11         if(cache.size() == n + 1){

12             cache[0]->next = cache[1]->next;

13             return head;   

14         }else {

15             return cache[0]->next;

16         }

17     }

 

你可能感兴趣的:(LeetCode)