双端栈——入栈与出栈

#include<stdio.h>

#define M 100

#define FALSE 0

#define TRUE 1

typedef int StackElemType;

typedef struct

{

 StackElemType Stack[M];

 int top[2];                    //top[0]和top[1]分别为两个栈顶指示器

}DqStack;



//初始化

void InitStack(DqStack *s)

{

 s->top[0]=-1;

 s->top[1]=M;

}



int Push(DqStack *s,StackElemType x,int i)//把数据元素x压入i号堆栈

{

   if(s->top[0]+1==s->top[1]) //栈已满

   return FALSE;

   switch(i)

    {

      case 0:

        s->top[0]++;

        s->Stack[s->top[0]]=x;

        break;

     case 1:

        s->top[1]--;

        s->Stack[s->top[1]]=x;

        break;

        default:

       return FALSE;

    }

 return TRUE;

}



int Pop(DqStack *s,StackElemType *x,int i)//把i号栈顶元素弹出

{

   switch(i)

    {

      case 0:

        if(s->top[0]==-1)

        return FALSE;

        *x=s->Stack[s->top[0]];

        printf("%d\n",*x);

        s->top[0]--;

        break;

     case 1:

        if(s->top[1]==M)

        return FALSE;

        *x=s->Stack[s->top[1]];

         printf("%d\n",*x);

         s->top[1]++;

         break;

         default:

     return FALSE;

    }

  return TRUE;

}



int main()

{

   DqStack  STA;

   int m,n,i,j;

   InitStack(&STA);

   printf("请选择入栈的位置(0号栈或者1号栈):");

   scanf("%d",&i);

   switch(i)

     {

        case 0:

          printf("\n请输入0号栈的长度:");

          scanf("%d",&m);

          printf("\n请输入0号栈的元素:");

          for(j=0;j<m;j++)

            {

                scanf("%d",&n);

                Push(&STA,n,i);

            }

          printf("\n0号栈入栈成功");

          printf("\n0号栈出栈元素为:\n");



          for(j=0;j<m;j++)

           {

                 Pop(&STA,&n,i);

           }

          break;

       case 1:

         printf("\n请输入1号栈的长度:");

         scanf("%d",&m);

         printf("\n请输入1号栈的元素:");

         for(j=0;j<m;j++)

          {

              scanf("%d",&n);

              Push(&STA,n,i);

          }

         printf("\n1号栈入栈成功\n");

         printf("\n1号栈出栈元素为:\n");



        for(j=0;j<m;j++)

         {

            Pop(&STA,&n,i);

         }

        break;

        default:

        printf("the input value is ERROR!");

 }

}

运行结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值