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. 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
//https://www.geeksforgeeks.org/delete-n-nodes-after-m-nodes-of-a-linked-list/
#include <iostream>
using namespace std;
struct LL {
int data;
struct LL *next;
};
typedef struct LL node;
void push (node **headref, int n) {
node *temp= (node *)malloc(sizeof(node));
temp->data= n;
temp->next= *headref;
*headref= temp;
return;
}
void print (node *n) {
while (n) {
cout<< n->data<< " ";
n= n->next;
}
}
void func (node **headref, int m, int n) {
if (m==0) {
node *temp= *headref;
while (n-->1)
temp= temp->next;
*headref= temp->next;
return;
}
node *temp1= *headref;
while (m-->1)
temp1= temp1->next;
node* temp2= temp1->next;
while (n-->1)
temp2= temp2->next;
temp1->next= temp2->next;
free(temp2);
return;
}
int main() {
node *head= NULL;
int m=5, n=2;
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);
print(head);
cout<<endl;
func(&head, m,n);
print(head);
}