简体   繁体   中英

The same expression but different result

So I am doing a question in leetcode. It is Implement Stack using Queues. If I submit this code below. It is accepted.

class Stack {
    public:
    queue<int> que;
    // Push element x onto stack.
    void push(int x) {
        que.push(x);
        for(int i=0;i<que.size()-1;i++){
            que.push(que.front());
            que.pop();
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        que.pop();
    }

    // Get the top element.
    int top() {
        return que.front();
    }

    // Return whether the stack is empty.
    bool empty() {
        return que.empty();
    }
};

but if I only change for(int i=0;i<que.size()-1;++i) to for(int i=0;i<=que.size()-2;i++) , I got Time limitation exceeded. Last executed input: push(1),empty().Could somebody tell me why??? Thanks

queue::size() returns a size_t which is basically an unsigned number. and a negative unsigned number converts to a huge number.

So queue::size()-1 --> huge number (0xFFFFFFFF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM