C# solution: slow&fast, dummy head


  • 0
    B
    public class Solution 
    {
        public ListNode RemoveNthFromEnd(ListNode head, int n) 
        {
            var dummy = new ListNode(-1);
            dummy.next = head;
    
            var pre = dummy;
            var slow = head;
            var fast = head;
    
            while(n > 1)
            {
                fast = fast.next;
                n--;
            }
    
            while(fast.next != null)
            {
                pre = slow;
                slow = slow.next;
                fast = fast.next;
            }
    
            pre.next = slow.next;
            slow.next = null;
    
            var newHead = dummy.next;
            dummy.next = null;
    
            return newHead;
        }
    }
    

Log in to reply
 

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