您的位置:首页 > 其它

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---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: