Answer to Question #238007 in C++ for Myname

Question #238007
Repeatedly Delete N nodes after M nodes of a Linked list:
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 until 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
The main part of the problem is to maintain proper links between nodes, make sure that all
corner cases are handled.
1
Expert's answer
2021-09-17T06:28:52-0400
#include <iostream>
using namespace std;


class Node
{
	public:
	int d;
	Node *nt;
};




void push(Node ** h_ref, int new_d)
{
	
	Node* new_n = new Node();


	new_n->d = new_d;


	new_n->nt = (*h_ref);


	(*h_ref) = new_n;
}


void printList(Node *h)
{
	Node *temp = h;
	while (temp != NULL)
	{
		cout<<temp->d<<" ";
		temp = temp->nt;
	}
	cout<<endl;
}


void skipMdeleteN(Node *h, int M, int N)
{
	Node *curr = h, *t;
	int count;
	while (curr)
	{
		for (count = 1; count < M &&
				curr!= NULL; count++)
			curr = curr->nt;


		if (curr == NULL)
			return;


		t = curr->nt;
		for (count = 1; count<=N && t!= NULL; count++)
		{
			Node *temp = t;
			t = t->nt;
			free(temp);
		}
		
		curr->nt = t;
		curr = t;
	}
}


int main()
{
	Node* h = NULL;
	int M=2, N=2;
	push(&h, 8);
	push(&h, 7);
	push(&h, 6);
	push(&h, 5);
	push(&h, 4);
	push(&h, 3);
	push(&h, 2);
	push(&h, 1);


	cout << "M = " << M<< " N = " << N << "\nGiven Linked list is :\n";
	printList(h);


	skipMdeleteN(h, M, N);


	cout<<"\nAfter deletion:\n";
	printList(h);


	return 0;
}



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS