-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeleteNNodesafterMNodes.java
53 lines (49 loc) · 1.28 KB
/
DeleteNNodesafterMNodes.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
/**
* 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; }
* }
*/
/*
Runtime: 0 ms, faster than 100.00% of Java online submissions for Delete N Nodes After M Nodes of a Linked List.
Memory Usage: 44.8 MB, less than 7.92% of Java online submissions for Delete N Nodes After M Nodes of a Linked List.
*/
class DeleteNNodesafterMNodes {
public ListNode deleteNodes(ListNode head, int m, int n) {
ListNode p=head;
while(p!=null)
{
int c=0,d=0;
ListNode a=p;
for(a=p,c=0;a!=null&&c<m-1;c++)
{
a=a.next;
}
if(a==null)
{
break;
}
p=a;
ListNode temp=a;
for(temp=a,d=0;temp!=null&&d<n;d++)
{
temp=temp.next;
}
if(temp==null)
{
p.next=null;
p=p.next;
}
else
{
p.next=temp.next;
p=p.next;
}
}
return head;
}
}