Latest

6/recent/ticker-posts

Write a program in c to insert and delete a middle element of a stack implemented using array

Write a program in c to insert and delete a midde element of a stack.

CODE:


 #include <limits.h>

#include <stdio.h>

#include <stdlib.h>


struct Stack {

int top;

unsigned capacity;

int* array;

};

struct Stack* createStack(unsigned capacity)

{

struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));

stack->capacity = capacity;

stack->top = -1;

stack->array = (int*)malloc(stack->capacity * sizeof(int));

return stack;

}


int isFull(struct Stack* stack)

{

return stack->top == stack->capacity - 1;

}


int isempty(struct Stack* stack)

{

return stack->top == -1;

}


void push(struct Stack* stack, int item)

{

if (isFull(stack))

return;

stack->array[++stack->top] = item;


}

int pop(struct Stack* stack)

{

if (isempty(stack))

return INT_MIN;

return stack->array[stack->top--];

}

int peek(struct Stack* stack)

{

if (isempty(stack))

return INT_MIN;

return stack->array[stack->top];

}

void deletemid(struct Stack* stack, int n,int curr)

{

if (isempty(stack) || curr == n)

return;

int x =peek(stack);

pop(stack);

deletemid(stack, n, curr+1);

if (curr != n/2)

push(stack,x);

}

void insertmid(struct Stack*stack, int n, int curr,int p)

{

    if (isempty(stack) || curr == n)

return;

int x =peek(stack);

    pop(stack);

    insertmid(stack, n, curr+1,p);

    if (curr == n/2-1)

push(stack,p);

push(stack,x);


}

int main()

{

struct Stack* stack = createStack(100);

printf("Enter no of elements you want to store initially\n");

int n;

scanf("%d",&n);

printf("Enter the elements\n");

int a[n];

for(int i=0;i<n;i++)

    {

        scanf("%d",&a[i]);

        push(stack,a[i]);

    }

    printf("Do you wanna insert or delete \n 1: insertion\n 2: deletetion\n");

    int t;

    scanf("%d",&t);

    if(t==2)

    deletemid(stack,n,0);

    else if(t==1)

    {

        printf("Enter the element you want to insert\n");

        int p;

        scanf("%d",&p);

        insertmid(stack,n,0,p);

    }

    printf("\nAfter operation\n");

    while (!isempty(stack))

{

int p=peek(stack);

pop(stack);

printf("%d  ",p);

}

return 0;

}

OUTPUT:




Post a Comment

0 Comments