implement of two stacks in an array in C
time complexity O(1)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct Stack
{
int top1;
int top2;
int capacity;
int* array;
};
void push1(struct Stack* stack,int num)
{
//printf("%d %d\n",stack->top1,stack->top2);
if(stack->top2-stack->top1==1)
{
printf("Stack Overflow");
exit(1);
}
else
{
stack->array[++stack->top1]=num;
}
//printf("%d %d\n",stack->top1,stack->top2);
}
void push2(struct Stack* stack,int num)
{
if(stack->top2-stack->top1==1)
{
printf("Stack Overflow");
exit(1);
}
else
{
stack->array[--stack->top2]=num;
}
//printf("%d %d\n",stack->top1,stack->top2);
}
int pop1(struct Stack* stack)
{
return stack->array[stack->top1--];
}
int pop2(struct Stack* stack)
{
return stack->array[stack->top2++];
}
int main()
{
int i,j,k,l,m,num,n;
printf("Enter the capacity of the stack\n");
scanf("%d",&m);
struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
stack->top1=-1;
stack->top2=m;
stack->capacity=m;
stack->array=(int*)malloc(sizeof(int)*stack->capacity);
while(1)
{
printf("1. Enter the elements in the stack1\n");
printf("2. Enter the elements in the stack2\n");
printf("3. Pop the elements from the stack1\n");
printf("4. Pop the elements from the stack2\n");
printf("5. Exit\n");
scanf("%d",&n);
switch(n)
{
case 1:
printf("Enter the elements you want to enter in the stack1=");
scanf("%d",&num);
push1(stack,num);
break;
case 2:
printf("Enter the elements you want to enter in the stack2=");
scanf("%d",&num);
push2(stack,num);
break;
case 3:
printf("%d is poped from stack1\n",pop1(stack));
break;
case 4:
printf("%d is poped from stack2\n",pop2(stack));
break;
case 5:
exit(0);
}
}
return 0;
}
No comments:
Post a Comment