GigiWithoutHadid
GigiWithoutHadid

Reputation: 369

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

Upvotes: 3

Views: 103

Answers (1)

Thomas Sparber
Thomas Sparber

Reputation: 2917

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)

Upvotes: 5

Related Questions