forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19.java
More file actions
37 lines (33 loc) · 865 Bytes
/
19.java
File metadata and controls
37 lines (33 loc) · 865 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
36
37
/**
* 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) {
if(n==0 || head==null)
return head;
if(n==1 && head.next==null)
return null;
ListNode fast=head;
ListNode slow=head;
while(n-->0)
fast=fast.next;
if(fast==null)
return slow.next;
while(fast.next!=null)
{
fast=fast.next;
slow=slow.next;
}
ListNode fwd=slow.next;
slow.next=fwd.next;
fwd.next=null;
return head;
}
}