剑指offer 用两个栈实现队列

来源:互联网 发布:贾平凹秦腔读后感知乎 编辑:程序博客网 时间:2024/05/02 02:35

题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。

思路:
我的第一反应就是 现将数据压入一个栈内,然后在需要取出时再压入另一个栈中,pop完之后再压入原来的栈内。。。

这样pop的复杂度就是O(n)了 网上有更高效的操作,即当s1压入另一个栈s2的时候,不着急存回去,而是再pop的时候直接在s2pop,当然push还是在s1中,当s2为0时,再将s1一次性压入s2中,这样会少很多元素转移的操作。

#include <cstdio>using namespace std;int main(){    int stack1[100010];    int stack2[100010];    int n;    int p1 = 0, p2= 0;    char op[10];    scanf("%d", &n);    while(n--){        scanf("%s", op);        if(op[1] == 'U'){            int x;            scanf("%d", &x);            stack1[p1++] = x;        }        else{            if(p2 == 0){                if(p1 == 0){                    printf("-1\n");                }                else{                    while(p1){                        stack2[p2++] = stack1[--p1];                    }                    printf("%d\n", stack2[--p2]);                }            }            else{                printf("%d\n", stack2[--p2]);            }        }    }    return 0;}
0 0
原创粉丝点击