-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLinkDelete.java
84 lines (74 loc) · 1.95 KB
/
LinkDelete.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
81
82
83
84
/*https://practice.geeksforgeeks.org/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/1*/
/*Pratik's solution*/
class Solution
{
static void linkdelete(Node head, int M, int N)
{
// your code here
Node cur = head;
int tempM = M, tempN = N;
while(cur!=null)
{
M = tempM;
N = tempN;
while(cur!=null && M!=1)
{
cur = cur.next;
M--;
}
while(N!=0)
{
if(cur!=null && cur.next != null)
{
cur.next = cur.next.next;
N--;
}
else
{
break;
}
}
if(cur==null || cur.next==null)break;
cur = cur.next;
}
}
}
/*Prateekshya's solution*/
class Solution
{
static void linkdelete(Node head, int M, int N)
{
Node temp = head;
int mCopy = M, nCopy = N;
//till we have more nodes
while (temp != null)
{
M = mCopy; N = nCopy;
//skip m nodes
while (M-- > 1)
{
//if list exhausts at any point, return
if (temp == null) return;
temp = temp.next;
}
//if list exhausted, return
if (temp == null) return;
//count n nodes
Node nextList = temp.next;
while (N-- > 0)
{
//if list exhausts at any point
//delete everything after last m nodes and return
if (nextList == null)
{
temp.next = null;
return;
}
nextList = nextList.next;
}
//delete n nodes and move
temp.next = nextList;
temp = nextList;
}
}
}