Cracking the coding interview--Q3.6
来源:互联网 发布:淘宝登录限制怎么办 编辑:程序博客网 时间:2024/04/29 10:13
题目
原文:
Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
译文:
写一个程序对一个栈进行升序排序,对栈是如何实现的,你不用任何假想,程序能用到的函数有:push,pop,peek,isEmpty
解答
使用一个附加的栈来模拟插入排序。将原栈中的数据依次出栈与附加栈中的栈顶元素比较, 如果附加栈为空,则直接将数据压栈。否则, 如果附加栈的栈顶元素大于从原栈中弹出的元素,则将附加栈的栈顶元素压入原栈。 一直这样查找直到附加栈为空或栈顶元素已经不大于该元素, 则将该元素压入附加栈。这样类似插入排序的方法,之间复杂度为O(n^2)。
代码如下:
import java.util.*;class Q3_6{public static Stack<Integer> sort(Stack<Integer> s) {Stack<Integer> r = new Stack<Integer>();while(!s.isEmpty()) {int tmp = s.pop();while(!r.isEmpty() && r.peek() > tmp) {s.push(r.pop());}r.push(tmp);}return r;}public static void main(String[] args){int[] a={3,6,2,9,7};Stack<Integer> s=new Stack<Integer>();for(int i=0;i<a.length;i++)s.push(a[i]);s=sort(s);while(!s.isEmpty()){System.out.print(s.pop()+" ");}}}
---EOF---
0 0
- Cracking the coding interview--Q3.6
- Cracking the coding interview--Q3.6
- Cracking the coding interview--Q3
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q3.2
- Cracking the coding interview--Q3.3
- Cracking the coding interview--Q3.4
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q3.2
- Cracking the coding interview--Q3.3
- Cracking the coding interview--Q3.4
- Cracking the coding interview--Q3.5
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q3.2
- Cracking the coding interview--Q3.3
- Cracking the coding interview--Q3.4
- Cracking the coding interview--Q3.5
- Cracking the Coding Interview
- HBase的领导人探讨Hadoop、BigTable和分布式数据库
- Linkedin CEO:我作CEO学到的最有价值的经验
- 聚类算法之BIRCH(Java实现)
- UVA 10054 - The Necklace 欧拉回路
- 《你必须知道的495个C语言问题》知识笔记及补充
- Cracking the coding interview--Q3.6
- 基于LIC算法的二维矢量场可视化
- hbase的export与import工具
- 学习java04
- HTML5+CSS3 学习小记
- HBase troubleshooting的一般思路
- 生成zimage的步骤
- 23种设计模式的基本介绍
- 【SDOI2011】【BZOJ】【P2242】【计算器】【题解】【快速幂+扩展欧几里得+高次同余方程/BSGS】