My 1ms Java solution may help u


  • 0
    /**
     * 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 pre = head, after = head;
    		while (n-- != 0) {
    			after = after.next;
    		}
    		if (after != null) {
    			while (after.next != null) {
    				pre = pre.next;
    				after = after.next;
    			}
    			pre.next = pre.next.next;
    		} else {
    			return head.next;
    		}
    		return head;
        }
    }

  • 0
    M

    might cause null pointer error at line "pre.next = pre.next.next;" , better using extra temp var to store previous pointer


  • 0

    The after node behind the pre node,so it is safe to use it.Thx for ur comment.


Log in to reply
 

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