https://leetcode.com/problems/remove-nth-node-from-end-of-list/

1. Use one-pass:

  1. //4 ms 10.4 MB
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode() : val(0), next(nullptr) {}
  8. * ListNode(int x) : val(x), next(nullptr) {}
  9. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. ListNode* removeNthFromEnd(ListNode* head, int n) {
  15. if(!head || (!head->next && n == 1)) return NULL;
  16. ListNode* dummy = new ListNode(-1);
  17. dummy->next = head;
  18. ListNode* curr1 = head;
  19. ListNode* curr2 = head;
  20. ListNode* prev = dummy;
  21. for(int i = 1; i < n; i++)
  22. curr1 = curr1->next;
  23. while(curr1->next){
  24. prev = curr2;
  25. curr1 = curr1->next;
  26. curr2 = curr2->next;
  27. }
  28. prev->next = curr2->next;
  29. return dummy->next;
  30. }
  31. };