-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBM9.java
More file actions
35 lines (34 loc) · 878 Bytes
/
BM9.java
File metadata and controls
35 lines (34 loc) · 878 Bytes
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
package NiukeTOP101;
public class BM9 {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
//添加表头
ListNode res = new ListNode(-1);
res.next = head;
//当前节点
ListNode cur = head;
//前序节点
ListNode pre = res;
ListNode fast = head;
//快指针先行n步
while(n != 0){
fast = fast.next;
n--;
}
//快慢指针同步,快指针到达末尾,慢指针就到了倒数第n个位置
while(fast != null){
fast = fast.next;
pre = cur;
cur = cur.next;
}
//删除该位置的节点
pre.next = cur.next;
//返回去掉头
return res.next;
}
}