Pages

Custom Search
Showing posts with label data structure. Show all posts
Showing posts with label data structure. Show all posts

Wednesday, October 5, 2011

Multiple Stack

Implementation of multiple stacks in a single linear array

//Include the necessary header files

#define SIZE 12 //Size of array(Vary as per need)
#define MAX 4 //Maximum number of stacks to store(vary as per need)

typedef struct
{
     int stk[SIZE];
     int top[MAX];
     int boundary[MAX];
}STACK;

void push();
void pop();
void display();

int main()
{
     STACK s;
     int choice, i, j, n;
     s.top[0] = s.boundary[0]=-1;
     printf("\nEnter the number of stacks you want to implement: ");
     scanf("%d", &n);
     for(i=1 ; i < n ; i++)
     {
            s.top[i] = s.boundary[i] = ((SIZE/n)*i)-1;
     }

     s.boundary[n] = SIZE-1;
     do
     {
            printf("\n\nOperation on three stacks:");
            printf("\n\n1.) Push");
            printf("\n2.) Pop");
            printf("\n3.) Display");
            printf("\n4.) Exit");
            printf("\n\nEnter your choice: ");
            scanf("%d", &choice);
            switch( choice )
            {
case 1: printf("\nEnter the stack number in which element is to be pushed(1- %d): ", n);
scanf("%d", &j);
if(j>n || j<1)
break;
push(&s, j);
break;
case 2: printf("\nEnter the stack number to pop element from(1-%d): ", n); scanf("%d", &j);
if(j>n || j<1);
break;
pop(&s, j);
break;

case 3: printf("\nEnter the stack number to display(1-%d): ", n);
scanf("%d", &j);
if(j>n || j<1)
break;
display(s, j);
break;
case 4: break;
default: printf("\nInvalid choice! Enter again.");
}
     }while(choice!=4);

     getch();
}

void push(STACK *p, int j)
{
  int i;
i=j-1;
if(p->top[i] == p->boundary[j])
{
printf("\nStack%d is overflow", j);
}
else
{
(p->top[i])++;
printf("\nEnter the element to push: ");
scanf("%d", &p->stk[p->top[i]]);
}
}

void pop(STACK *p, int j)
{
int i;
i=j-1;
if(p->top[i] == p->boundary[i])
{
printf("\nStack%d is underflow", j);
}
else
{
printf("\nPopped element: %d", p->stk[(p->top[i])--]);
}
}

void display(STACK s, int j)
{
int i, k;
i=j-1;
if(s.top[i] == s.boundary[i])
{
printf("\nStack%d is empty", j);
}
else
{
printf("\nStack%d is: \n", j);
for(k=s.top[i]; k>s.boundary[i]; k--)
{
printf("\n%d", s.stk[k]);
}
}
}


Custom Search