-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRemoveNthFromEnd.java
More file actions
60 lines (39 loc) · 1.06 KB
/
RemoveNthFromEnd.java
File metadata and controls
60 lines (39 loc) · 1.06 KB
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
39
40
41
42
43
44
45
package recursion_and_dynamic_programming;
/**
* @Author: Wenhang Chen
* @Description:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
* @Date: Created in 14:07 11/18/2019
* @Modified by:
*/
public class RemoveNthFromEnd {
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
int k = 1;
public ListNode removeNode(ListNode pre, ListNode cur, int n) {
// 先递归到最底层
if (cur.next != null) {
removeNode(cur, cur.next, n);
}
// 再回来,头结点需要单独考虑
if (k == n) {
if (pre != null) {
pre.next = cur.next;
k++;
return pre;
} else {
return cur.next;
}
}
k++;
return cur;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
return removeNode(null, head, n);
}
}