-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_nth_node.java
More file actions
40 lines (39 loc) · 1.09 KB
/
remove_nth_node.java
File metadata and controls
40 lines (39 loc) · 1.09 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
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null) return null;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode pre=dummy,cur=head,next=head;
int i=0;
while(i++!=n) next=next.next;
while(next!=null) {
pre=cur;
cur=cur.next;
next=next.next;
}
pre.next=cur.next;
cur.next=null;
return dummy.next;
}
}
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode dummy=new ListNode(0);
dummy.next=head;
r(head,dummy,n);
return dummy.next;
}
public int r(ListNode node,ListNode pre,int n) {
if(node==null) return 0;
int pos=r(node.next,node,n)+1;
if(pos==n) {
pre.next=node.next;
node.next=null;
}
return pos;
}
}