My easy one pass solution in java but not the fast, I want know the way to optimize it.


  • -1

    Here is my code:

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode l1 = head, l2 = head;
            while(l1.next != null){
                if(n > 0){
                    l1 = l1.next;
                    n--;
                }
                else{
                    l1 = l1.next;
                    l2 = l2.next;
                }
            }
            
            if(n == 1){
                head = head.next;
            }
            else{
                l2.next = l2.next.next;
            }
            
            return head;
        }
    }

Log in to reply
 

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