Java与算法(1)
来源:互联网 发布:自制qq头像软件 编辑:程序博客网 时间:2024/05/29 18:53
Java与算法(1)
题目: 设计一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
要求:
1 pop,push,getMin操作的时间复杂度都是O(1) 2 设计的栈类型可以使用现成的栈结构
public class Stack_getMIn { Stack<Integer> stack_data ; Stack<Integer> stack_min ; public Stack_getMIn(Stack<Integer> stack_data,Stack<Integer> stack_min) { this.stack_data = stack_data; this.stack_min = stack_min;} public void push(int newNum) { if (stack_min.isEmpty()) {stack_min.push(newNum);} else if (stack_min.peek()>newNum) {stack_min.push(newNum);} stack_data.push(newNum);} public int pop() {int value = stack_data.peek();if (stack_min.peek()==value) {stack_min.pop();}return value;} public int getMin() { return stack_min.peek();}public static void main(String[] args) {Stack<Integer> data = new Stack<>();Stack<Integer> min = new Stack<>();Stack_getMIn stack_getMIn = new Stack_getMIn(data,min);stack_getMIn.push(5);stack_getMIn.push(20);stack_getMIn.push(0);System.out.println(stack_getMIn.getMin());stack_getMIn.pop();System.out.println(stack_getMIn.getMin()); }}
题目:
编写一个类,使用两个栈实现队列,支持队列的基本操作(add,poll,peek)
public class StackToQueue {Stack<Integer> s1 ;Stack<Integer> s2;public StackToQueue(Stack<Integer> s1,Stack<Integer> s2) {this.s1 = s1;this.s2 = s2;}public void add(int num) {s1.add(num);}public int peek() {if (s2.isEmpty()) {while (!s1.isEmpty()) {s2.push(s1.pop());}}return s2.peek();}public int pool() {if (s2.isEmpty()) {while (!s1.isEmpty()) {s2.push(s1.pop());}}return s2.pop();}public static void main(String[] args) {Stack<Integer> s1 = new Stack<>();Stack<Integer> s2 = new Stack<>();StackToQueue stackToQueue = new StackToQueue(s1, s2);stackToQueue.add(5);stackToQueue.add(4);stackToQueue.add(3);System.out.println(stackToQueue.peek());}}
阅读全文
0 0
- Java与算法(1)
- Java数据结构与算法分析(1)--算法复杂度概念
- java数据结构与算法1
- Java与算法(2)
- Java与算法(3)
- Java与算法(4)
- Java与算法(5)
- Java与算法(6)
- Java与算法(7)
- Java与算法(8)
- Java与算法(9)
- Java与算法(10)
- Java与算法(11)
- Java与算法(12)
- Java与算法(13)
- 数据结构与算法(Java描述)-1、数据结构与算法总述以及抽象数据类型
- Java 数据结构与算法(1)-------------求最大公约数
- java数据结构与算法分析学习1(递归函数)
- Day03-JavaScript01
- 《红皮书》总结
- SQL入门书籍内容汇总
- 学生操作系统“三种文件”
- 学生管理操作系统-总览
- Java与算法(1)
- Hive开发经验总结
- MariaDB数据库安装完需要初始化操作
- sizeof与strlen
- 使用JDBCTemplate实现与Spring结合,方法公用 ——Spring配置(applicationContext.xml)
- python 发送http请求填坑
- USB协通讯议(很好的一篇文章)
- Openstack Neutron扩展实现细节(QOS)
- 又遇到vmware不能启动了(vmware12/Deepin15.4(4.9.0kernel))