/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { //1. create a dummyHead before the real head ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode first = head; int length = 0; //as long as first is not null, we increase length //and keep moving first while(first != null) { length++; first = first.next; } //use length - n to locate the node we are going to delete length -=n; first = dummyHead; while(length > 0) { length--; first = first.next; } first.next = first.next.next; return dummyHead.next; } }