-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-19.java
More file actions
47 lines (43 loc) · 1.38 KB
/
lc-19.java
File metadata and controls
47 lines (43 loc) · 1.38 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
46
47
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int i = 1;
int j = 1;
ListNode fast = head, slow = head;
while(fast.next != null) {
slow = slow.next;
fast = fast.next;
i++;
j++;
if(fast.next == null) {
break;
}else{
fast = fast.next;
j++;
}
}
//得到链表长度,以及慢指针所在的位置
//如果n在慢指针前面,则从头指针开始遍历,反之则从慢指针开始遍历
if(j-n+1 > i) {
//从慢指针开始遍历
while(i++ < j-n) { //这里本来是j-n+1
slow = slow.next;
}
System.out.println(slow.val);
//删除操作
ListNode t = slow.next;
slow.next = slow.next==null?null:slow.next.next;
t = null;
return head;
}else {
int k = 0;
ListNode nhead = new ListNode(-1);
nhead.next = head;
ListNode hp = nhead;
while(k++ < j-n) nhead = nhead.next; //j-n+1
ListNode t = nhead.next;
nhead.next = (nhead.next == null?null:nhead.next.next);
t = null;
return hp.next;
}
}
}