leetcode_225题——Implement Stack using Queues (队列,栈)

Implement Stack using Queues

  Total Accepted: 9609 Total Submissions: 31710My Submissions

 

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

 

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

 

Hide Tags
  Stack Data Structure
Hide Similar Problems
  (E) Implement Queue using Stacks
 
      这道题要用队列来实现栈,所以只需要用一个队列就可以了
 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 
 5 queue<int> qu1;
 6 
 7  // Push element x onto stack.
 8     void push(int x) {
 9         qu1.push(x);
10     }
11 
12     // Removes the element on top of the stack.
13     void pop() {
14         if(!qu1.empty())
15         {
16             int n=qu1.size()-1;
17             int re;
18             while(n--)
19             {
20                 re=qu1.front();
21                 qu1.pop();
22                 qu1.push(re);
23             }
24             qu1.pop();
25         }
26         else
27             return;
28     }
29 
30     // Get the top element.
31     int top() {
32         int n=qu1.size();
33         int re;
34         int res;
35         while(n--)
36         {
37             re=qu1.front();
38             if(n==0)
39                 res=re;
40             qu1.pop();
41             qu1.push(re);
42         }
43         return res;
44     }
45 
46     // Return whether the stack is empty.
47     bool empty() {
48         if(qu1.empty())
49             return 1;
50         else
51             return 0;
52     }
53 
54 
55 int main()
56 {
57 
58 }

 

你可能感兴趣的:(LeetCode)