Best C# Solution One pass O(n) runtime O(1) space


  • 1
    K
     * 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) 
        {
            ListNode fakeHead = new ListNode(0);
            fakeHead.next = head;
            ListNode fast = fakeHead;
            ListNode slow = fakeHead;
            int i = 0;
            while(i < n + 1){
                fast = fast.next;
                i++;
            }
            
            while(fast != null){
                fast = fast.next;
                slow = slow.next;
            }
            
            slow.next = slow.next.next;
            return fakeHead.next;
        }
    }

Log in to reply
 

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