/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ publicclassSolution{ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode dummy = new ListNode(0); dummy.next = head; ListNode slow = dummy; ListNode fast = dummy; for (int i = 0; i <= n; i++){ fast = fast.next; } // if the two pointers are n nodes away, excluding themselves, then the while condition is "fast != null" // if the two pointers are n - 1 nodes away, the condition should be "first.next != null" while (fast != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return dummy.next; } }