Answer to Question #238001 in C for Aadi

Question #238001
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-16T08:20:08-0400
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

typedef struct Node* List;

List init();
List add(List l, int x);
void print(List l);
List rep_delete(List l, int m, int n);
List clean(List l);


int main() {
    List l;
    int i;


    l = init();
    for (i=1; i<=8; i++) 
        l = add(l, i);
    print(l);
    l = rep_delete(l, 2, 2);
    print(l);


    l = clean(l);


    return 0;
}

List init() {
    return (List) NULL;
}

List add(List l, int x) {
    List res;
    if (!l) {
        res = (struct Node *) malloc(sizeof(struct Node));
        res->next = NULL;
        res->data = x;
        return res;
    }
    res = l;
    while (l->next)
        l = l->next;
    l->next = (struct Node *) malloc(sizeof(struct Node));
    l->next->next = NULL;
    l->next->data = x;
    return res;
}

void print(List l) {
    if (!l)
        return;
    printf("%d", l->data);
    l = l->next;
    while (l) {
        printf("->%d", l->data);
        l = l->next;
    }
    printf("\n");
}

List rep_delete(List l, int m, int n) {
    int i = 1;
    int keep = 1;
    List res = l;
    struct Node* tmp;

    if (!l) {
        return l;
    }

    while (l->next) {
        i++;
        if (keep) {
            if ( i == m) {
                keep = 0;
                i = 0;
            }
            l = l->next;
        }
        else {
            tmp = l->next;
            l->next = tmp->next;
            free(tmp);
            if (i == n) {
                keep = 1;
                i = 0;
            }
        }
    }
    return res;
}

List clean(List l) {
    struct Node* tmp;
    while (l) {
        tmp = l->next;
        free(l);
        l = tmp;
    }
    return NULL;
}

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