当前位置:网站首页>如何仅用递归函数和栈操作逆序一个栈
如何仅用递归函数和栈操作逆序一个栈
2022-07-25 07:38:00 【dlz456】
题目:一个栈依次压入1,2,3,4,5,那么从栈顶到栈底分别为:5,4,3,2,1。将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构。
我自己的理解:

如上图,将左边的栈通过逆序转换为右边的栈,右边的栈最下面是3,因此最先要把3压进去,也就说明在从左边的栈中提取元素时,要最后提取到三,因此就说明是从栈底元素开始到栈顶元素依次进行遍历。但是对于左边来说,3在栈顶,1在栈底,和我们想要的顺序不同,因此这里还需要写一个递归。对于右边的栈来说,在压入第一个元素3的时候,要求栈为空,也就是意味着我们在对初始的左边栈进行数据提取时,应该采用pop而不是peek。
代码实现如下:
package text3;
import java.util.Stack;
public class class1 {
public class1() {
}
public static int getlast(Stack<Integer> stack) {
int result=stack.pop();
if(stack.empty()) {
return result;
}else {
int last=getlast(stack);
stack.push(result);
return last;
}
}
public static void reverse(Stack<Integer> stack) {
if(stack.empty()) {
return;
}
int a=getlast(stack);
reverse(stack);
stack.push(a);
}
}
边栏推荐
- Huawei wireless device sta black and white list configuration command
- [unity introduction program] basic concepts - 2D collider collider 2D
- What products and funds should novices invest in first?
- Introduction to Manhattan distance
- Use cyclegan to train self-made data sets, popular tutorials, and get started quickly
- [ES6] function parameters, symbol data types, iterators and generators
- Offline base tile, which can be used for cesium loading
- 钉钉最新版,怎么清除登录手机号历史记录数据
- while(~scanf(“%d“, &n)) 等价于 while(scanf(“%d“,&n)!=EOF)
- 全新8.6版本SEO快排系统(可源码级搭建)
猜你喜欢

使用CycleGAN训练自己制作的数据集,通俗教程,快速上手

Lidar construction map (overlay grid construction map)

北京内推 | 微软STCA招聘NLP/IR/DL方向研究型实习生(可远程)
P1086 [NOIP2004 普及组第二题] 花生采摘
![[unity entry program] make my first little game](/img/e7/5dcb113c7fabd73ed632fb29619369.png)
[unity entry program] make my first little game

Problems during nanodet training: modulenotfounderror: no module named 'nanodet' solution

曼哈顿距离简介

Have you got the advanced usage of pytest?

Beijing internal promotion | Microsoft STCA recruits nlp/ir/dl research interns (remote)

Analysis of difficulties in diagramscene project
随机推荐
Million level element optimization: real-time vector tile service based on PG and PostGIS
深度学习制作数据集时,从长视频中指定每隔多少帧提取一张图像到指定文件路径的方法
新库上线| CnOpenDataA股上市公司股东信息数据
About --skip networking in gbase 8A
[paper notes] effective CNN architecture design guided by visualization
【微信小程序】全局样式、局部样式、全局配置
Cluster chat server: summary of project problems
A fast method of data set enhancement for deep learning
9 best engineering construction project management systems
Completely replace the redis+ database architecture, and JD 618 is stable!
SAP queries open Po (open purchase order)
3. Promise
Common cross domain scenarios
Simulation Implementation of list
Elasticserach里delete_by_query的机制是什么?
nanodet训练时出现问题:ModuleNotFoundError: No module named ‘nanodet‘的解决方法
Learn no when playing 10. Is enterprise knowledge management too boring? Use it to solve!
使用CycleGAN训练自己制作的数据集,通俗教程,快速上手
[pytorch] the most common function of view
BOM overview