Java simple one-pass solution with two pointers


  • 0
    X
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast=head;
            ListNode slow=head;
            while(n>0){
                fast=fast.next;
                n--;
            }
    
            if(fast==null) return slow.next;
            
            while(fast.next!=null){
                fast=fast.next;
                slow=slow.next;
            }
            
            slow.next=slow.next.next;
            return head;
        }
    }

Log in to reply
 

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