Java solution with explanation!

  • 0

    Java solution with explanation!

    The code itself is easy. In order to avoid the edge case, especially when the head is needed to be
    So the easy way i think is to add a dummy point,

    ListNode  dummy = new ListNode(0); = head;

    so that once the code is finished, you just need
    to return;

    correct me if i am wrong. Thx!!

    As for deleting the last nth node, you have to go back, i think the key point to
    solve the problem is to find the last (n+1)th node, so that make
    the (n+1) = (n+1);

     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode dummy = new ListNode(0);
   = head;
            ListNode slow = dummy;
            ListNode fast = head;
            for (int i = 0; i<n; i++){
            while(fast != null){
                fast =;

  • 0

    @lujingyang1029 so i have a question,if n==1,then whether the" =" will generate "NullPointerException"?

  • 0

    Sorry for answering late. As slow start from the node dummy, which is 0 in this case;

    when fast reach null, slow is at node 1, so = will make the linked list above


Log in to reply

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