Pretty fast solution in Java


  • 3
    P
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode first = head;
            ListNode second = head;
            
            for(int i =0; i<n; i++) {
                first = first.next;
            }
            if(first == null) {
                head = head.next;
                return head;
            }
            while(first.next != null) {
                first = first.next;
                second = second.next;
            }
            second.next = second.next.next;
            return head;
        }
    }

  • 0
    Y

    upvote for the clarification of the process with 2 separated loops. i've gone through other discussions without any complete comprehension of this kind of process until i've seen yours. so, many thx.


  • 0
    Y

    sorry i'd better say this in a comment but not an answer...


Log in to reply
 

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