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.
C
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void push( struct Node ** head_ref,
int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf ( "%d " , temp->data);
temp = temp->next;
}
printf ( "" );
}
void skipMdeleteN( struct Node *head,
int M, int N)
{
struct Node *curr = head, *t;
int count;
while (curr)
{
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++)
{
struct Node *temp = t;
t = t->next;
free (temp);
}
curr->next = t;
curr = t;
}
}
int main()
{
struct Node* head = NULL;
int M=2, N=3;
push(&head, 10);
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf ("M = %d, N = %d
Given Linked list is :",
M, N);
printList(head);
skipMdeleteN(head, M, N);
printf (
"Linked list after deletion is :" );
printList(head);
return 0;
}
|
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!