双端栈——入栈与出栈

#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!");

 }

}

 

运行结果


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

双端栈——入栈与出栈

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭