Delete N nodes after M nodes of a linked list

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int el;
	struct node *next;	
} Node;

typedef Node* List;

void deleteNafterM(List l, int n, int m) {

	int count = 0;
	Node *prev = NULL, *next;

	while (l) {

		count++;
		next = l->next;

		if (prev) {
			if (count == n) {
				prev->next = next;
				prev = NULL;
				count = 0;
			} 

			free(l);

		} else if (count == m) {
			prev = l;
			prev->next = NULL;
			count = 0;
		} 

		l = next;
	}
}

void printList(List l) {
	while (l) {
		printf("%d", l->el);
		l = l->next;
	}

	printf("\n");
}

inline Node* newNode(int el) {
	Node *node = (Node *)malloc(sizeof(Node));
	node->el = el;
	node->next = NULL;

	return node;
}

List createList(int n) {
	List l = newNode(1);

	Node *curr = l;
	int i;

	for (i = 2; i <= n; i++) {
		curr->next = newNode(i);
		curr = curr->next;
	}

	return l;
}

int  main(int argc, char const *argv[])
{
	List l = createList(10);

	deleteNafterM(l, 2, 3);

	printList(l);

	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s