2个栈实现一个队列

   今天动手写了个两个栈实现一个队列的代码,第一次写博客,希望为时不晚。

 

  思想很简单,就是一个栈S1用于入队,另一个栈S2用于出队。

 


#include <stdio.h>
#include <stdlib.h>

typedef int EleType;

struct _strcutNode;
struct _strcutQueue;

typedef struct _strcutNode  * Stack;
typedef struct _strcutQueue * Queue;

struct _strcutNode
{

 EleType Key;
 struct _strcutNode * Next; 
};

struct _strcutQueue
{
 Stack S1;
 Stack S2;
};

void Push(Stack S,EleType Key)
{
 Stack tmp; 
 tmp =(Stack) malloc(sizeof(struct _strcutNode));
 tmp->Key = Key;
 tmp->Next = S->Next ;
 S->Next  =tmp;
}

EleType Pop(Stack S)
{
 Stack tmp;

 EleType re;

 if(S != NULL)
 {

  tmp = S->Next ;
  re= tmp->Key ;
  S->Next = tmp->Next ;
  free(tmp);

  return re;
  
 }
}


void CreatQueue(Queue Q)
{

 Q->S1 =(Stack) malloc(sizeof(struct _strcutNode ));

 Q->S2 =(Stack) malloc(sizeof(struct _strcutNode ));

 Q->S1 ->Next = NULL;
 Q->S2 ->Next  = NULL;


}

void EnQueue(Queue Q,EleType Key)
{

 printf("%d入队\n",Key);
 Push(Q->S1,Key);

}

void DeQueue(Queue Q)
{
 
 if(Q->S2 ->Next !=NULL)//S2不为空时,直接将S2栈顶元素出队
 {
   printf("出队:%d\n",  Pop(Q->S2 ));

 }
 else if(Q->S1 ->Next !=NULL) //Q->S2 ->Next == NULL ,将S1栈除了栈底所有元素弹出并压入S2中,

                                                                                         // 那么S1栈底元素就是要出队的元素

{
  while(Q->S1->Next->Next  != NULL)
   Push(Q->S2 ,  Pop(Q->S1 ));
  printf("出队:%d\n", Pop(Q->S1));
 }else                      //Q->S2 ->Next == NULL ,Q->S1 ->Next ==NULL
 {
  printf("队列为空");    
 }
}

void
main()
{


 Queue Q;


 Q =(Queue)malloc(sizeof(struct _strcutQueue ));
 CreatQueue(Q);

 EnQueue(Q,1);
 EnQueue(Q,2);
 EnQueue(Q,3);
 EnQueue(Q,4);
 EnQueue(Q,5);


  DeQueue(Q);
  DeQueue(Q);
  DeQueue(Q);
 EnQueue(Q,7);
 EnQueue(Q,8);

 EnQueue(Q,9);
 EnQueue(Q,10);
 EnQueue(Q,11);

  DeQueue(Q);
  DeQueue(Q);
  DeQueue(Q);
  DeQueue(Q);
  DeQueue(Q);
  DeQueue(Q);
 EnQueue(Q,-1);
 DeQueue(Q);


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值