Cracking the coding interview--Q3.6
2014-02-07 23:25
357 查看
题目
原文:
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---
原文:
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---
相关文章推荐
- Cracking the coding interview--Q3.6
- Cracking the coding interview--Q16.1-Q16.10
- Cracking The Coding Interview 1.1
- Cracking The Coding Interview 1.7
- Cracking the coding interview--Q19.4
- Cracking the coding interview--Q19.6
- Cracking the coding interview--Q3.2
- 【Cracking the coding interview】Q1.5(替换字符串)
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目6
- 《Cracking the Coding Interview》——第12章:测试——题目5·
- 《Cracking the Coding Interview》——第13章:C和C++——题目10
- 《Cracking the Coding Interview》题目汇总
- 《Cracking the Coding Interview》——第16章:线程与锁——题目3
- 《Cracking the Coding Interview》——第18章:难题——题目7
- Cracking the Coding Interview(Trees and Graphs)
- Cracking the coding interview--Q9.7
- 判断一个二叉树是否是平衡二叉树 Cracking the coding interview 4.1
- Cracking the coding interview--Q8.6
- Cracking the coding interview---中文解析版
- 《Cracking the Coding Interview》读书笔记