-
Notifications
You must be signed in to change notification settings - Fork 0
/
19.java
80 lines (76 loc) · 1.99 KB
/
19.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode left = dummy;
ListNode right = dummy;
for(int i=0;i<n;i++){
right = right.next;
}
while(right.next!=null){
left=left.next;
right = right.next;
}
left.next = left.next.next;
return dummy.next;
}
}
// 第二次做法,两次遍历
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy.next;
int length = 0;
while(cur!=null){
length++;
cur = cur.next;
}
cur = dummy;
for(int i = 0;i<length-n;i++){
cur = cur.next;
}
if(cur.next==null){
cur.next = null;
}
else{
cur.next = cur.next.next;
}
return dummy.next;
}
}
// 第三次做法,一次遍历(核心在于先走出差距,类似于链表相交)
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode left = dummy;
ListNode right = dummy;
while(n-->0){
right = right.next;
}
while(right.next!=null){
left = left.next;
right = right.next;
}
left.next = left.next.next;
return dummy.next;
}
}