WHAT'S NEW?
Loading...

Contiguous List Operations


/*Contiguous List operations*/
#include<stdio.h>
#define max 5

struct clist {
    int items[max];
    int L_index;
};

void insrt(struct clist *c) {
    int pos, x, i;
    if (c->L_index == max - 1) {
        printf("\nList is full");
        return;
    }
    printf("\nEnter the position: ");
    scanf("%d", &pos);
    if (pos > (c->L_index + 1)) {
        printf("\nInvalid position for the contiguous list");
        return;
    }
    printf("\nEnter data t insert in list: ");
    scanf("%d", &x);
    i = c->L_index;
    while (i >= pos) {
        c->items[i + 1] = c->items[i];
        i--;
    }
    c->items[pos] = x;
    c->L_index++;
}

void delt(struct clist *c) {
    int pos, x, i;
    if (c->L_index == -1) {
        printf("\nList empty!");
        return;
    }
    printf("\nEnter the position: ");
    scanf("%d", &pos);
    if (pos > c->L_index) {
        printf("\nInvalid position!");
        return;
    }
    x = c->items[pos];
    i = pos;
    while (i <= c->L_index) {
        c->items[i] = c->items[i + 1];
        i++;
    }
    printf("\nThe deleted item is: %d", x);
    c->L_index--;
}

void traverse(struct clist *c) {
    int i;
    if (c->L_index == -1) {
        printf("\nList is empty!");
        return;
    }
    printf("\nThe elements of the list are:\n");
    for (i = 0; i <= c->L_index; i++) {
        printf("%5d", c->items[i]);
    }
}

void search(struct clist *c) {
    int x, i;
    if (c->L_index == -1) {
        printf("\nList is empty!");
        return;
    }
    printf("\nEnter the data to search: ");
    scanf("%d", &x);
    for (i = 0; i <= c->L_index; i++) {
        if (x == c->items[i]) {
            printf("\nThe given data is found in ths list.");
            return;;
        }
    }
    printf("\nThe given data is not found in the list.");
}

void main() {
    struct clist cl;
    int ch;
    cl.L_index = -1;
    while (1) {
        printf("\nMENU");
        printf("\n1.Insert at any position");
        printf("\n2.Delete from any position");
        printf("\n3.Traverse and print all elements");
        printf("\n4.Search a particular value");
        printf("\n5.Exit\n\nEnter your choice: ");
        scanf("%d", &ch);
        switch (ch) {
        case 1:
            insrt(&cl);
            break;
        case 2:
            delt(&cl);
            break;
        case 3:
            traverse(&cl);
            break;
        case 4:
            search(&cl);
            break;
        case 5:
            exit(1);
        default:
            printf("\nInvalid Choice\n");
        }
    }
}

0 comments:

Post a Comment