Advertisement
nikunjsoni

19

Mar 19th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* removeNthFromEnd(ListNode* head, int n) {
  14.         ListNode *dummy = new ListNode(0, head);
  15.         ListNode *slow, *fast;
  16.         slow = fast = dummy;
  17.         while(n--) fast = fast->next;
  18.         while(fast->next){
  19.             slow = slow->next;
  20.             fast = fast->next;
  21.         }
  22.         slow->next = slow->next->next;
  23.         return dummy->next;
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement