标签:
class Solution { public: void push(int node) { if (stack1.size() != 0) stack1.push(node); else{ int n = (int)stack2.size(); for (int i = 0; i < n; i++){ stack1.push(stack2.top()); stack2.pop(); } stack1.push(node); } } int pop() { if (stack2.size() != 0) { int temp = stack2.top(); stack2.pop(); return temp; } else { int n = (int)stack1.size(); for (int i = 0; i < n - 1; i++){ stack2.push(stack1.top()); stack1.pop(); } int temp =stack1.top(); stack1.pop(); return temp; } } private: stack<int> stack1; stack<int> stack2; };
在网上找到一种更高效的方法:入栈时直接将元素压入stack1,出栈时检查stack2,如果为空将stack1中的元素压入stack2,如果不为空直接将stack2栈顶元素出栈,很巧妙
class Solution { public: void push(int node) { stack1.push(node); } int pop() { int temp; if (!stack2.empty()) { temp = stack2.top(); stack2.pop(); return temp; } else { int n = stack1.size(); for (int i = 0; i < n; i++){ stack2.push(stack1.top()); stack1.pop(); } temp = stack2.top(); stack2.pop(); return temp; } }
标签:
原文地址:http://www.cnblogs.com/code-changeworld/p/4542125.html