Java solution with explanation!


  • 0
    L

    Java solution with explanation!

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

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

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

    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)th.next = (n+1)th.next.next;

    /**
     * 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);
            dummy.next = head;
            ListNode slow = dummy;
            ListNode fast = head;
            
            for (int i = 0; i<n; i++){
                fast= fast.next;    
            }
            while(fast != null){
                fast = fast.next;
                slow= slow.next;
            }
            slow.next = slow.next.next;
            
            return dummy.next;
        }
    }
    

  • 0

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


  • 0
    L

    Sorry for answering late. As slow start from the node dummy, which is 0 in this case;
    (0)->1->2->null;

    when fast reach null, slow is at node 1, so slow.next = slow.next.next will make the linked list above
    like
    (0)->1->null;

    right?


Log in to reply
 

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