Javascript Program To Delete N Nodes After M Nodes Of A Linked List
Last Updated :
30 Mar, 2022
Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.
Difficulty Level: Rookie
Examples:
Input:
M = 2, N = 2
Linked List: 1->2->3->4->5->6->7->8
Output:
Linked List: 1->2->5->6
Input:
M = 3, N = 2
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->2->3->6->7->8
Input:
M = 1, N = 1
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->3->5->7->9
The main part of the problem is to maintain proper links between nodes, make sure that all corner cases are handled. Following is C implementation of function skipMdeleteN() that skips M nodes and delete N nodes till end of list. It is assumed that M cannot be 0.
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .next = null ;
}
}
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
function printList(head)
{
var temp = head;
while (temp != null )
{
document.write(temp.data + " " );
temp = temp.next;
}
document.write( "<br/>" );
}
function skipMdeleteN(head, M , N)
{
var curr = head, t;
var count;
while (curr != null )
{
for (count = 1; count < M &&
curr != null ; count++)
curr = curr.next;
if (curr == null )
return ;
t = curr.next;
for (count = 1; count <= N &&
t != null ; count++)
{
var temp = t;
t.next;
}
curr.next = t;
curr = t;
}
}
var head = null ;
var M = 2, N = 3;
head = push(head, 10);
head = push(head, 9);
head = push(head, 8);
head = push(head, 7);
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
document.write(
"M = " +M+ ", N = " + N +
"<br/>Given Linked list is :<br/>" );
printList(head);
skipMdeleteN(head, M, N);
document.write(
"<br/>Linked list after deletion is :<br/>" );
printList(head);
</script>
|
Output:
M = 2, N = 3
Given Linked list is :
1 2 3 4 5 6 7 8 9 10
Linked list after deletion is :
1 2 6 7
Time Complexity:
O(n) where n is number of nodes in linked list.
Auxiliary Space: O(1)
Please refer complete article on Delete N nodes after M nodes of a linked list for more details!
Share your thoughts in the comments
Please Login to comment...