-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN19RemoveNthFromEnd.java
50 lines (40 loc) · 1.08 KB
/
N19RemoveNthFromEnd.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
package LeetCode;
public class N19RemoveNthFromEnd {
private static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
private static ListNode removeNthFromEnd(ListNode head, int n) {
int count = 0;
ListNode p = head;
while(head!=null){
count++;
head = head.next;
}
head = p;
if(count == n){
return head.next;
}
// count = 8 n=2 6
for(int i=0;i<count-n-1;i++){
p = p.next;
}
p.next = (p.next==null)?null:p.next.next;
return head;
}
public static void main(String[] args) {
ListNode l2 = new ListNode(1);
l2.next = new ListNode(2);
l2.next.next = new ListNode(3);
l2.next.next.next = new ListNode(4);
l2.next.next.next.next = new ListNode(5);
ListNode listNode= removeNthFromEnd(l2,2);
while (listNode!=null){
System.out.println(listNode.val);
listNode= listNode.next;
}
}
}