Fork me on GitHub

Remove Nth Node From End of List

This is a cliche problem, all I have learned is don’t forget the corner case of head node in linkedlist problem!!!!!!!!!

Descrption

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

Solution

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
/**
* 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) {
if (head == null) return null; //corner case

ListNode current = head, nextNNode = head;
//Find the next n-th node
while(nextNNode != null && n > 0) {
nextNNode = nextNNode.next;
n -= 1;
}
if (nextNNode == null) return head.next; //Remove the head

//Traverse the remaining node
while(nextNNode.next != null) {
nextNNode = nextNNode.next;
current = current.next;
}
current.next = current.next.next;
return head;
}
}