利用两个栈模拟队列

数据结构

队列

笔试题:利用两个栈模拟队列
image

思路

将元素x先全部放进s1栈中,再将s1栈中元素进行出栈操作(进行逆序放置),放入到s2栈中(模拟队列入队操作) ,再将s2中元素进行出栈(模拟队列出队操作)。
​ 1.s1满栈,s2空
​ 2.s1不满,s2空
​ 3.s1满,s2不空(无法进行入队操作)

代码

/**
  * @name:		enQueue
  * @brief  	入队操作
  * @param  
  				@s1
				@s2
				@x
  * @retval 	bool
  * @date 		2024/04/28
  * @note   	补充 注意 说明
  */
  
//将元素放进s1中后将s1中元素出栈入队s2
bool enQueue(s1,s2,int x)
{
    //存放s1出栈的元素
    int temp;
    //分s1满和不满两种情况,不满时则继续往里面放元素
    if( s1->top +1 = maxSize)
    {
        //s2也分空与不空的情况
        if(isEmpty(s2))
        {
            while(isEmpty(s1))
            {
                pop(s1,&temp);
                push(s2,temp);
            }
        }
        else
		{
			printf("无法进行入队操作\n");
            return false;
    	}
	}
    else
     	pop(s1,x);
    return true;
}

//s2中元素进行出队
/**
  * @name:		enQueue
  * @brief  	出队操作
  * @param  
				@s2
  * @retval 	bool
  * @date 		2024/04/28
  * @note   	补充 注意 说明
  */
bool deQueue(s2)
{
    //如果s2为空无法输出,不空则输出
    if(isEmpty(s2))
    {
        printf("s2为空 无法输出\n");
        return false;
    }
    else
	{
		while( ! isEmpty(s1) )
		{
			pop(s1,&temp); //把s1元素暂时存储在temp中
			push(s2,temp); //把temp中的元素入队到s2
		}
        pop(s2,&x);
    }
	return true;
}
posted @ 2024-04-28 23:55  luxiaolim  阅读(3)  评论(0编辑  收藏  举报