jayati

Remove Nth Node From End of List

Nov 28th, 2022
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 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* temp= new ListNode();
  15.         temp->next = head;
  16.         ListNode* fast = temp;
  17.         ListNode* slow = temp;
  18.         for(int i=1;i<=n;i++)
  19.         {
  20.             fast=fast->next;
  21.         }
  22.         while(fast->next!=nullptr)
  23.         {
  24.             fast=fast->next;
  25.             slow=slow->next;
  26.         }
  27.         ListNode* lost = slow->next;
  28.         slow->next=slow->next->next;
  29.         delete(lost);
  30.         return temp->next;
  31.  
  32.        
  33.     }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment