Click here to Skip to main content
15,905,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am trying to implement two stacks in one array.
The push operation of both the stacks works.
But in the popping, when i pop an element from the first stack then the remaining elements in second stack shift to left but a zero will be placed at the second stack's top. How to avoid this zero?
The code is ginven below.
Somebody please help.

C
#include
#include
#define max 9
int i,stk[max]={NULL},top1=-1,top2=-1,btn1=0,btn2=0;
void display()
{
  printf("\nThe stack is...\n\n");
  for(i=0;i<=top2;i++)
    printf("%d  ",stk[i]);
}
void push_first()
{
  if(top1!=max)
  {
    for(i=top2+1;i>=btn2;i--)
      stk[i]=stk[i-1];
    top2++;
    btn2++;
    top1++;
    printf("\nEnter the element:");
    scanf("%d",&stk[top1]);
  }
  display();
}
void push_second()
{
  if(top2!=max)
  {
    top2++;
    printf("\nEnter the element:");
    scanf("%d",&stk[top2]);
  }
  display();
}
void pop_first()
{
  if(top1!=btn1-1)
  {
    printf("\nPopped element :%d",stk[top1]);
    for(i=btn2-1;i<top2;i++)
    {
      stk[i]=stk[i+1];
      stk[i+1]='\0';
    }
    btn2--;
    top1--;
  }
  display();
}
void pop_second()
{
  if(top2!=top1)
  {
    printf("\nPopped element :%d",stk[top2]);
    top2--;
  }
  display();
}
int main()
{
  int ch;
  clrscr();
  do
  {
    printf("\n\n  MENU");
    printf("\n1.Push first\n2.Push second\n3.Pop first\n4.Pop second\n5.Display\n6.Exit");
    printf("\nEnter your choice:");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1:push_first();
      break;
    case 2:push_second();
      break;
    case 3:pop_first();
      break;
    case 4:pop_second();
      break;
    case 5:display();break;
    case 6:exit(0);
    default:printf("\nInvalid choice!");
    }
  }while(ch!=6);
  getch();
  return(0);
}
Posted
Updated 1-Apr-10 23:51pm
v4

It could be more
efficient, simple and secure

to place the bottoms of the stacks -
at the both ends of an array... :)


Added,LP:
correct.
create one stack at the bottom of the array, push would increment the index; and one stack at the top of the array, where push would decrement the index. No need to move data in the array at all!
 
Share this answer
 
v2
Just decrement top2--;
after the loop in pop_first() :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900