leetcode- 232. Implement Queue using Stacks

使用栈实现队列:

将栈中的元素取出再存入一次就是队列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
         
    }
     
    /** Push element x to the back of queue. */
    void push(int x) {
       s.push(x);
 
    }
     
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
 
        stack<int> s1;
        while(!s.empty())
        {
            int t=s.top();
            s.pop();
            s1.push(t);
             
        }
        int t=s1.top();
        s1.pop();
        while(!s1.empty())
        {
            int t=s1.top();
             
            s.push(t);
            s1.pop();
        }
        return t;
         
    }
     
    /** Get the front element. */
    int peek() {
        stack<int> s_tem=s;
        while(s_tem.size()>1)
        {
         s_tem.pop();
        }
        return s_tem.top();
        
    }
     
    /** Returns whether the queue is empty. */
    bool empty() {
        return s.empty();
         
    }
    private:
    stack<int> s;
    
};
 
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

  

更简单一点实现,pop和top的实现互相借助时:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class MyQueue {
public:
    stack<int> S1, S2;
    /** Initialize your data structure here. */
    MyQueue() {
            
    }
     
    /** Push element x to the back of queue. */
    void push(int x) {
        S1.push(x);
    }
     
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int v = -1;
        if (!S2.empty()) { v = S2.top(); S2.pop();}
        else {
            while(!S1.empty()) {
                S2.push(S1.top());
                S1.pop();
            }
            v = S2.top();
            S2.pop();
        }
        return v;
    }
     
    /** Get the front element. */
    int peek() {
        if (!S2.empty()) return S2.top();
        else {
            while(!S1.empty()) {
                S2.push(S1.top());
                S1.pop();
            }
            return S2.top();
        }
    }
     
    /** Returns whether the queue is empty. */
    bool empty() {
        return (S1.empty()) && (S2.empty());
    }
};
 
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

  

posted @   hahahaf  阅读(153)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示