LeetCode Q19 Remove Nth Node From End of List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 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;
}
}