Share my C# solution


  • 0
    Y

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • public int val;
      
    • public ListNode next;
      
    • public ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode RemoveNthFromEnd(ListNode head, int n) {

       var newHeader=new ListNode(0);
       newHeader.next=head;
       var pre=newHeader;
       var runner=head;
       int counter = 0;
       
       var slowruner=head;
       
       while(runner != null)
       {
           runner=runner.next;
           counter += 1;
           pre=pre.next;
           slowruner=slowruner.next;
           
           if(counter == n)
           {
               pre = newHeader;
               slowruner = head;
           }
       }
       
       pre.next=slowruner.next;
       
       return newHeader.next;
      

      }
      }


Log in to reply
 

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