Advertisement here

Remove Nth Node From End of List - Leetcode solution

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

Problem Statement

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

Solution(C++):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int i=1;
        
        ListNode* mundi=head;
        ListNode* p=head;
        
        
        
        while(head->next!=NULL)
        {
             if(i>n)
               p=p->next;
            
            head=head->next;
            i++;
            
           
            
        }
        
        
       
        if(p==mundi && i!=n+1) return p->next;
        
        p->next=p->next->next;
        
        return mundi;
    }
};
Next Post Previous Post
No Comment
Add Comment
comment url
Advertisement here