栈和队列面试题

栈和队列的实现方式参考博客:https://blog.csdn.net/cx2479750196/article/details/80493848

1、两个栈实现一个队列


typedef struct QueuewithStack{
    SeqStack entry;
    SeqStack exit;
}QueuewithStack;
typedef char QueueType;
****************************************************************************************************************************
void QueuewithStackInit(QueuewithStack* q){
    if (q == NULL){
        return;
    }
    SeqStackInit(&q->entry);
    SeqStackInit(&q->exit);

}
void QueuewithStackPush(QueuewithStack* q,QueueType value){
    if (q == NULL){
        return;
    }
    QueueType tmp;//查看exit中是否有元素,循环取栈顶元素插入entry中
    while (SeqStackFindTop(&q->exit, &tmp)){
        SeqStackPop(&q->exit);
        SeqStackPush(&q->entry, tmp);
    }
    //此时exit为空
    SeqStackPush(&q->entry, value);
}
void QueuewithStackPop(QueuewithStack* q){
    if (q == NULL){
        return;
    }
    QueueType tmp;//出队列时要将数据放在exit中然后不断pop
    while (SeqStackFindTop(&q->entry, &tmp)){
        SeqStackPop(&q->entry);
        SeqStackPush(&q->exit, tmp);
    }
    SeqStackPop(&q->exit);
}
int QueuewithStack_FindTop(QueuewithStack* q, QueueType* value){
    if (q == NULL||value==NULL){
        return 0;
    }
    QueueType tmp;//将entry中的元素倒腾到exit中,然后才能准确的取出队首元素
    while (SeqStackFindTop(&q->entry, &tmp)){
        SeqStackPop(&q->entry);
        SeqStackPush(&q->exit, tmp);
    }
    int ret=SeqStackFindTop(&q->exit,value);
    return ret;
}

2、两个队列实现一个栈


typedef struct StackwithQueue{
    SeqQueue q1;
    SeqQueue q2;
}StackwithQueue;
typedef char  StackwithQueueType;
void Init(StackwithQueue* Sq){
    if (Sq == NULL){
        return;
    }
    QueueInit(&Sq->q1);
    QueueInit(&Sq->q2);

}
void Push(StackwithQueue* Sq, StackwithQueueType data){
    if (Sq == NULL){
        return;
    }
    //无论如何不可能两个队同时为空,也不可能两个
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值