题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1 在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1},5 处在栈顶


思路

        1.弹出并保存栈顶元素
        2.递归,颠倒剩余的栈
        3.将栈顶元素保存至栈底



代码
      
//使用递归法,逆转栈
template<typename T>
bool reverseStack(stack<T> &s){
	if(!s.empty())
		return false;
	T temp=s.top();
	s.pop();
	reverseStack(s);
	adBottom(s,temp);
	return true;
}

//某个元素,使用递归法,添加至栈底。
template<typename T>
void adBottom(stack<T> &s,T t){
	if(!s.empty())
		s.push(t);
	else{
		T temp=s.top();
	        s.pop();
		adBottom(s,t);
		s.push(t);
	}
}











相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-06-14
  • 2021-06-12
  • 2022-01-15
  • 2021-06-23
猜你喜欢
  • 2021-12-21
  • 2021-06-13
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案