LeetCode 19. Remove Nth Node From End of List

LeetCode 19. Remove Nth Node From End of List_第1张图片

 这道题我看了答案,使用了双指针法来解决问题,

class Solution {
public:
     ListNode* removeNthFromEnd(ListNode* head, int n) {
         ListNode* dummy = new ListNode(0, head);
         ListNode* first = head;
         ListNode* second = dummy;

         for (int i = 0; i < n; ++i) {
             first = first->next;
         }
        
         while (first) {
             first = first->next;
             second = second->next;
         }

         second->next = second->next->next;
         ListNode* ans = dummy->next;
         
         delete dummy;
         
         return ans;
     }
};

你可能感兴趣的:(LeetCode,leetcode)