forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeleteMnodesAfterNnodes.java
67 lines (58 loc) · 1.72 KB
/
DeleteMnodesAfterNnodes.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
package com.rampatra.linkedlists;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/6/15
* @time: 7:43 PM
*/
public class DeleteMnodesAfterNnodes {
/**
* Deletes {@param n} nodes after every {@param m} nodes in {@param list}
* till it reaches the end of {@param list}.
*
* @param list
* @param m
* @param n
* @param <E>
*/
public static <E extends Comparable<E>> void deleteMnodesAfterNnodes(SingleLinkedList<E> list,
int m, int n) {
SingleLinkedNode<E> curr1 = list.head, curr2;
while (curr1 != null) {
// skip m nodes
for (int i = 1; curr1.next != null && i < m; i++) {
curr1 = curr1.next;
}
// delete n nodes
curr2 = curr1;
for (int i = 0; curr2 != null && i <= n; i++) {
curr2 = curr2.next;
}
curr1.next = curr2;
curr1 = curr1.next;
}
}
public static void main(String[] args) {
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
linkedList.add(7);
linkedList.add(5);
linkedList.add(9);
linkedList.add(4);
linkedList.add(6);
linkedList.add(1);
linkedList.add(2);
linkedList.add(7);
linkedList.add(5);
linkedList.add(9);
linkedList.add(4);
linkedList.add(6);
linkedList.add(1);
linkedList.add(2);
linkedList.printList();
deleteMnodesAfterNnodes(linkedList, 3, 2);
linkedList.printList();
}
}