C# solution using dummy head and two pointers


  • 0
    H

    public class Solution {

    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode first = dummy;
        ListNode second = dummy;
        int count = 0;
        
        // Find the node to remove
        while( first != null){
            first = first.next;
            
            if(count > n){
                second = second.next;
            }
            
            count++;
        }
        
        // Remove node pointed by second.next
        second.next = second.next.next;
        
        return dummy.next;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.