左思右想不会呀,结果嘞 看了答案焕然大悟。下面这个代码是错误的的 请问哪里错误了
1 class Solution 2 { 3 public: 4 void push(int node) { 5 stack1.push(node); 6 } 7 8 int pop() { 9 int a ; 10 if(stack2.empty() == true){ 11 while(stack1.empty() != true){ 12 a = stack1.top(); 13 stack2.push(a); 14 stack1.pop(); 15 } 16 } 17 return stack2.top(); 18 stack2.pop(); 19 } 20 21 private: 22 stack<int> stack1; 23 stack<int> stack2; 24 };
正确的:
1 class Solution 2 { 3 public: 4 void push(int node) { 5 stack1.push(node); 6 } 7 8 int pop() { 9 int a ; 10 if(stack2.empty() == true){ 11 while(stack1.empty() != true){ 12 a = stack1.top(); 13 stack2.push(a); 14 stack1.pop(); 15 } 16 } 17 a = stack2.top(); 18 stack2.pop(); 19 return a ; 20 } 21 22 private: 23 stack<int> stack1; 24 stack<int> stack2; 25 };
return 这个要小心 ,return完了之后,下面的不会执行的了
python:
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def __init__(self): 4 self.s1 = [] 5 self.s2 = [] 6 def push(self, node): 7 # write code here 8 self.s1.append(node); 9 def pop(self): 10 # return xx 11 if( self.s2 ==[]): 12 while self.s1: 13 a = self.s1[-1] 14 self.s2.append(a) 15 self.s1.pop() 16 return self.s2.pop()