Tuesday, 20 September 2011

TWO STACKS IN A SINGLE ARRAY IN C

Another important program which has been asked in many technical interviews is : WAP to implement two stacks in a single array so that either of the stacks become full only when the entire array is full.



Here's the C program :


#include<stdio.h>
#define SIZE 10
struct stack
{
 int top1,top2;
 int array[SIZE];
}s;

void push1(int x)
{
 if((s.top1)<(s.top2-1))
  s.array[++(s.top1)]=x;
 else
  printf("OVERFLOW IN STACK 1\n");
}

void push2(int x)
{
 if((s.top2)>(s.top1+1))
  s.array[--(s.top2)]=x;
 else
  printf("OVERFLOW IN STACK 2\n");
}

int pop1()
{
 if((s.top1)>=0 && (s.top1)<(s.top2))
  printf("The element popped out from stack1 is %d\n",s.array[(s.top1)--]);
 else
  printf("UNDERFLOW IN STACK 1\n");
}

int pop2()
{
 if((s.top2)<SIZE && (s.top2)>(s.top1))
  printf("The element popped out from stack 2 is %d\n",s.array[(s.top2)++]);
 else
  printf("UNDERFLOW IN STACK 2\n");
}

main()
{
 s.top1 = -1,s.top2 = 5;
 int ch,x;
 while(1)
 {
  printf("IMPLENTATION OF TWO STACKS IN SINGLE ARRAY\n");
  printf("Enter your choice of operation\n");
  printf("1.PUSH TO STACK 1\n2.PUSH TO STACK 2\n3.POP FROM STACK 1\n4.POP FROM STACK 2\n 5.EXIT\n");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1: printf("Enter element to be pushed to stack 1\n");
          scanf("%d",&x);
          push1(x);
          break;
   case 2: printf("Enter element to be pushed to stack 2\n");
          scanf("%d",&x);
          push2(x);
          break;
   case 3: pop1();
          break;
   case 4: pop2();
          break;
   default: return;
  }
 }
}


No comments:

Post a Comment