1
+ /*
2
+ Author: King, wangjingui@outlook.com
3
+ Date: Dec 12, 2014
4
+ Problem: Remove Nth Node From End of List
5
+ Difficulty: Medium
6
+ Source: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
7
+ Notes:
8
+ Given a linked list, remove the nth node from the end of list and return its head.
9
+ For example,
10
+ Given linked list: 1->2->3->4->5, and n = 2.
11
+ After removing the second node from the end, the linked list becomes 1->2->3->5.
12
+ Note:
13
+ Given n will always be valid.
14
+ Try to do this in one pass.
15
+
16
+ Solution: head---back------front------>NULL
17
+ | |
18
+ ---> n <----
19
+ */
20
+
21
+ /**
22
+ * Definition for singly-linked list.
23
+ * public class ListNode {
24
+ * int val;
25
+ * ListNode next;
26
+ * ListNode(int x) {
27
+ * val = x;
28
+ * next = null;
29
+ * }
30
+ * }
31
+ */
32
+ public class Solution {
33
+ public ListNode removeNthFromEnd (ListNode head ,int n ) {
34
+ ListNode dummy =new ListNode (0 );
35
+ ListNode back =dummy ,front =dummy ;
36
+ dummy .next =head ;
37
+ while (n -- !=0 )front =front .next ;
38
+ while (front .next !=null ) {
39
+ front =front .next ;
40
+ back =back .next ;
41
+ }
42
+ back .next =back .next .next ;
43
+ return dummy .next ;
44
+ }
45
+ }