面试题 03.01. 三合一

面试题 03.01. 三合一

思路:记录栈的size

为数组开辟内存 int *a; a = new int[1000];

class TripleInOne {
public:
    int *stack;
    int top[3];
    int stackSize;
    TripleInOne(int stackSize):stackSize(stackSize) {
        stack = new int[stackSize*3];//此处创建新内存卡了1小时
        top[0]=top[1]=top[2]=0;
    }
    
    void push(int stackNum, int value) {
        if(top[stackNum]<stackSize)
            stack[stackSize*stackNum + top[stackNum]++]=value;
    }
    
    int pop(int stackNum) {
        if(top[stackNum] <= 0) 
            return -1;
        else 
            return stack[stackSize*stackNum + (--top[stackNum])];
    }
    
    int peek(int stackNum) {
        if(top[stackNum] <=0 )
            return -1;  
        else 
            return stack[stackSize*stackNum + (top[stackNum]-1)];
    }
    
    bool isEmpty(int stackNum) {
        return top[stackNum]==0;
    }
};
发布了248 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38603360/article/details/105146985