您的位置:首页 > 其它

Cracking the coding interview--Q3.6

2014-11-12 16:28 197 查看
原文:

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。

使用一个附加的栈来模拟插入排序。将原栈中的数据依次出栈与附加栈中的栈顶元素比较, 如果附加栈为空,则直接将数据压栈。否则, 如果附加栈的栈顶元素大于从原栈中弹出的元素,则将附加栈的栈顶元素压入原栈。 一直这样查找直到附加栈为空或栈顶元素已经不大于该元素, 则将该元素压入附加栈。

package chapter_3_StacksandQueues;

import java.util.Scanner;

/**
*
* 写程序将一个栈按升序排序。对这个栈是如何实现的,你不应该做任何特殊的假设。 程序中能用到的栈操作有:push | pop | peek | isEmpty。
*
*/
public class Question_3_6 {

/**
* 使用插入排序方法排序
*/
public static void sort(Stack_3_5 stack) {
Stack_3_5 stack2 = new Stack_3_5(10);
while(!stack.isEmpty()) {
int data = stack.top();
stack.pop();
// 如果当前stack2栈顶元素大于当前需排序元素,元素出栈暂时存储在stack栈顶
while(!stack2.isEmpty() && stack2.top() > data) {
stack.push(stack2.top());
stack2.pop();
}
stack2.push(data);
}
}

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
String strs[] = string.split(" ");
Stack_3_5 stack = new Stack_3_5(10);
for(int i=0; i< strs.length; i++) {
stack.push(Integer.parseInt(strs[i]));
}
sort(stack);
while(!stack.isEmpty()) {
int data = stack.top();
System.out.format("%3d", data);
}
}
}


参考自:http://www.hawstein.com/posts/3.6.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法