用两个栈实现一个队列的功能

xiaoxiao2026-08-31  19

【转】http://hi.baidu.com/liangjw821/blog/item/74c98ed520f299cc51da4b86.html 原题: 用两个栈实现一个队列的功能? 思路: 假设两个栈 A 和B,且都为空。 可以认为栈 A 为提供入队列的功能,栈 B 提供出队列的功能。 入队列: 入栈 A 出队列: 1 如果栈B 不为空,直接弹出栈 B 的数据。 2 如果栈 B 为空 2.1 若A不为空,则依次弹出栈 A 的数据,放入栈 B 中,再弹出栈 B 的数据。 2.1 若A为空,则队列为空。 int enqueue(stack s1,elemtp x) { PUSH(s1,x); return(1); } ElementType dequeue(stack s2,stack s1) { if(!empty(s2))//s2 is not empty { return POP(s2); } else { if(empty(s1) { printf("队列为空"); exit(0); } else { while(!empty(s1) { ElementType t; POP(s1,t); push(s2,t); } return pop(s2); } } }
转载请注明原文地址: https://www.6miu.com/read-5052163.html

最新回复(0)